在GuzzleHttp上处理客户端错误异常

Inf*_*o E 1 laravel guzzle laravel-5

我试图处理请求状态代码,基本上检查状态是否为200,以防不处理。我正在使用一个名为“ GuzzleHttp \ Client”的程序包,当出现404时,它给我一个错误:

Client error: `GET https://api.someurl---` resulted in a `404 Not Found` response:
{"generated_at":"2017-09-01T16:59:25+00:00","schema":"","message":"No events scheduled for this date."}
Run Code Online (Sandbox Code Playgroud)

但是比在屏幕上以我想要更改的格式显示,所以我试图捕捉并在视图上提供不同的输出。但是不起作用,它仍然给我红色屏幕错误。

try {
            $client = new \GuzzleHttp\Client();
            $request = $client->request('GET', $url);
            $status = $request->getStatusCode();
            if($status == 200){
                return $status;

            }else{

                throw new \Exception('Failed');
            }

        } catch (\GuzzleHttp\Exception\ConnectException $e) {
            //Catch errors
            return $e->getStatusCode();

        }
Run Code Online (Sandbox Code Playgroud)

小智 5

好吧,如果您想坚持尝试,就可以做这样的事情:

$client = new \GuzzleHttp\Client();

try {
    $request = $client->request('GET', $url);
} catch (\GuzzleHttp\Exception\ConnectException $e) {
    // This is will catch all connection timeouts
    // Handle accordinly
} catch (\GuzzleHttp\Exception\ClientException $e) {
    // This will catch all 400 level errors.
    return $e->getResponse()->getStatusCode();
}

$status = $request->getStatusCode();
Run Code Online (Sandbox Code Playgroud)

如果未触发捕获,$request则将成功,这意味着状态代码为200。但是,要捕获400错误,请确保http_errors在设置时将request选项设置为true $client