吞食:处理400个错误的请求 [英] Guzzle: handle 400 bad request

查看:83
本文介绍了吞食:处理400个错误的请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using Guzzle in Laravel 4 to return some data from another server, but I can't handle Error 400 bad request

 [status code] 400 [reason phrase] Bad Request

使用:

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

如何解决? 谢谢,

推荐答案

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

As written in Guzzle official documentation: http://guzzle.readthedocs.org/en/latest/quickstart.html

如果将例外请求选项设置为true,则会抛出GuzzleHttp \ Exception \ ClientException,引发400个级别的错误

A GuzzleHttp\Exception\ClientException is thrown for 400 level errors if the exceptions request option is set to true

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

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.

}

这篇关于吞食:处理400个错误的请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆