咕噜咕噜:处理400个错误请求

2022-08-30 14:45:17

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

 [status code] 400 [reason phrase] Bad Request

用:

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

如何解决?谢谢


答案 1

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

如果异常请求选项设置为 true,则会针对 400 级错误引发 GuzzleHttp\异常\客户端异常

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

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.

}

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

对请求使用 http_errors => false 选项。


推荐