Guzzle:处理400错误请求

32

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

 [status code] 400 [reason phrase] Bad Request

使用:

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

如何解决这个问题? 谢谢。


1
你是说你“无法处理400错误”? - Laurence
1
当收到此错误时,页面停止并显示此错误消息(我想处理此异常)。 - mwafi
2个回答

73

根据 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.

}

我遇到了一个错误:“Undefined property: GuzzleHttp\Psr7\Response::$result”。 - Jaber Al Nahian
我们还应该添加 if ($e->hasResponse()){ },因为有时候 $e->getResponse() 会返回 null,在处理 RequestException 中的 504 错误时也是如此。 - userbloom

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

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


这是对我有效的解决方案。在我的情况下,我不知道为什么请求不会进入异常状态。将http_errors设置为false并获取状态码以处理异常是我所做的。感谢这个解决方案。 - Dave Cruise
try catch这个短语不够优雅,这个回答应该更好一些。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接