【问题标题】:Guzzle: handle 400 bad requestGuzzle:处理 400 个错误请求
【发布时间】:2014-09-22 07:23:51
【问题描述】:

我在 Laravel 4 中使用 Guzzle 从另一台服务器返回一些数据,但我无法处理错误 400 错误请求

 [status code] 400 [reason phrase] Bad Request

使用:

$client->get('http://www.example.com/path/'.$path,
            [
                'allow_redirects' => true,
                'timeout' => 2000
            ]);

如何解决? 谢谢,

【问题讨论】:

  • “无法处理错误 400”是什么意思?
  • 收到此错误时,页面停止并显示此错误消息(我要处理此异常)

标签: php laravel bad-request guzzle


【解决方案1】:

Guzzle 官方文档中写的:http://guzzle.readthedocs.org/en/latest/quickstart.html

如果异常请求选项设置为 true,则会针对 400 级错误抛出 GuzzleHttp\Exception\ClientException

为了正确处理错误,我会使用以下代码:

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

try {

    $response = $client->get(YOUR_URL, [
        'connect_timeout' => 10
    ]);
        
    // Here the code for successful request

} catch (RequestException $e) {

    // Catch all 4XX errors 
    
    // To catch exactly error 400 use 
    if ($e->hasResponse()){
        if ($e->getResponse()->getStatusCode() == '400') {
                echo "Got response 400";
        }
    }

    // You can check for whatever error status code you need 
    
} catch (\Exception $e) {

    // There was another exception.

}

【讨论】:

  • 有了这个我得到错误“未定义的属性:GuzzleHttp\Psr7\Response::$result”
  • 我们还应该添加 if ($e->hasResponse()){ } 因为有时 $e->getResponse() 在 504 的情况下返回 null,这也由 RequestException 处理
【解决方案2】:
$client->get('http://www.example.com/path/'.$path,
            [
                'allow_redirects' => true,
                'timeout' => 2000,
                'http_errors' => true
            ]);

在请求中使用 http_errors => false 选项。

【讨论】:

  • 这是对我有用的解决方案。就我而言,我不知道为什么请求不会出现异常。将 http_errors 设置为 false 并获取状态代码以处理异常是我所做的。感谢这个解决方案
猜你喜欢
  • 2016-11-18
  • 1970-01-01
  • 2017-04-10
  • 1970-01-01
  • 1970-01-01
  • 2018-08-13
  • 2019-09-01
  • 1970-01-01
  • 2018-12-06
相关资源
最近更新 更多