当Guzzle检测到400或500错误时如何防止崩溃?

kyo*_*kyo 4 php laravel guzzle laravel-5

我正在使用PHP guzzle

我试过了

public static function get($url) {

    $client = new Client();

    try {
        $res = $client->request('GET',$url);
        $result = (string) $res->getBody();
        $result = json_decode($result, true);
        return $result;
    }
    catch (GuzzleHttp\Exception\ClientException $e) {
        $response = $e->getResponse();
        $responseBodyAsString = $response->getBody()->getContents();
    }

}
Run Code Online (Sandbox Code Playgroud)

我不断得到

在此输入图像描述

当Guzzle检测到400或500错误时如何防止崩溃?

我只是希望我的应用程序继续运行和加载.

cee*_*yoz 5

所以,我敢打赌你的get()函数存在于命名空间中App\Http\Controllers,这意味着:

catch (GuzzleHttp\Exception\ClientException $e) {
Run Code Online (Sandbox Code Playgroud)

实际上被解释为,如果你写:

catch (App\Http\Controllers\GuzzleHttp\Exception\ClientException $e) {
Run Code Online (Sandbox Code Playgroud)

出于显而易见的原因,抛出这种情况并不例外.

您可以通过执行以下操作来修复命名空间问题:

catch (\GuzzleHttp\Exception\ClientException $e) {
Run Code Online (Sandbox Code Playgroud)

(注意领先\)或推杆:

use GuzzleHttp\Exception\ClientException;
Run Code Online (Sandbox Code Playgroud)

namespace声明和捕获之后的文件顶部ClientException.

请参见http://php.net/manual/en/language.namespaces.basics.php.

  • 并且,如果OP想要返回身体,即使它是4xx或5xx,OP也可以使用Guzzle的[`http_errors`设置](http://docs.guzzlephp.org/en/stable/request-options. HTML#HTTP的错误). (2认同)