php Guzzle:处理 400 个错误请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25040436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Guzzle: handle 400 bad request
提问by mwafi
I'm using Guzzle in Laravel 4 to return some data from another server, but I can't handle Error 400 bad request
我在 Laravel 4 中使用 Guzzle 从另一台服务器返回一些数据,但我无法处理错误 400 错误请求
[status code] 400 [reason phrase] Bad Request
using:
使用:
$client->get('http://www.example.com/path/'.$path,
[
'allow_redirects' => true,
'timeout' => 2000
]);
how to solve it? thanks,
如何解决?谢谢,
回答by Hpatoio
As written in Guzzle official documentation: http://guzzle.readthedocs.org/en/latest/quickstart.html
正如 Guzzle 官方文档中所写:http://guzzle.readthedocs.org/en/latest/quickstart.html
A GuzzleHttp\Exception\ClientException is thrown for 400 level errors if the exceptions request option is set to true
如果异常请求选项设置为 true,则会针对 400 级错误引发 GuzzleHttp\Exception\ClientException
For correct error handling I would use this code:
为了正确的错误处理,我会使用这个代码:
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->getResponse()->getStatusCode() == '400') {
echo "Got response 400";
}
// You can check for whatever error status code you need
} catch (\Exception $e) {
// There was another exception.
}
回答by adam
$client->get('http://www.example.com/path/'.$path,
[
'allow_redirects' => true,
'timeout' => 2000,
'http_errors' => true
]);
Use http_errors => false option with the request.
在请求中使用 http_errors => false 选项。