【问题标题】:Handling Client Errors exceptions on GuzzleHttp处理 GuzzleHttp 上的客户端错误异常
【发布时间】:2018-02-10 19:14:06
【问题描述】:

我正在尝试处理请求状态码,主要是检查状态是否为 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."}

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

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();

        }

【问题讨论】:

  • 那么您是想从您的 guzzle 请求中捕获 404 异常还是只是连接异常?
  • 我正在尝试检查 404 或其他状态代码,例如 200

标签: laravel laravel-5 guzzle


【解决方案1】:

好的,如果你想坚持使用 try-catch,你想做这样的事情:

$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();

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

【讨论】:

    猜你喜欢
    • 2015-08-18
    • 2019-07-27
    • 2015-04-26
    • 1970-01-01
    • 2011-02-19
    • 2019-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多