Guzzle: handle 400 bad request

44,405

Solution 1

As written in Guzzle official documentation: 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

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

}

Solution 2

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

Use http_errors => false option with the request.

Share:
44,405
mwafi
Author by

mwafi

PHP Developer at Grow knowledge www.wokcraft.com

Updated on July 21, 2020

Comments

  • mwafi
    mwafi almost 4 years

    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
    

    using:

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

    how to solve it? thanks,

  • Dave Cruise
    Dave Cruise almost 5 years
    This is the solution that worked for me. In my case, I have no idea why is the request will not go to exception. setting the http_errors to false and get the status code to handle exception is what i did. thx for this solution
  • Jaber Al Nahian
    Jaber Al Nahian over 4 years
    With this I am getting erro "Undefined property: GuzzleHttp\Psr7\Response::$result"
  • Anil
    Anil almost 4 years
    we should also add if ($e->hasResponse()){ } as sometimes $e->getResponse() returns null in case of 504 which is also handled by RequestException