Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent crashing when Guzzle detect 400 or 500 error?

I'm using PHP guzzle

I have tried

public static function get($url) {

    $client = new Client();

    try {
        $res = $client->request('GET',$url);
        $result = (string) $res->getBody();
        $result = json_decode($result, true);
        return $result;
    }
    catch (GuzzleHttp\Exception\ClientException $e) {
        $response = $e->getResponse();
        $responseBodyAsString = $response->getBody()->getContents();
    }

}

I kept getting

enter image description here

How to prevent crashing when Guzzle detecct 400 or 500 error ?

I just want my application to continue running and loading.

like image 550
code-8 Avatar asked Oct 18 '17 19:10

code-8


2 Answers

So, I'd bet your get() function exists in a namespace like App\Http\Controllers, which means this:

catch (GuzzleHttp\Exception\ClientException $e) {

is actually being interpreted as if you'd written:

catch (App\Http\Controllers\GuzzleHttp\Exception\ClientException $e) {

For obvious reasons, no exception of that kind is being thrown.

You can fix the namespacing issue by doing:

catch (\GuzzleHttp\Exception\ClientException $e) {

(note the leading \) or putting:

use GuzzleHttp\Exception\ClientException;

at the top of the file after the namespace declaration and catching just ClientException.

See http://php.net/manual/en/language.namespaces.basics.php.

like image 113
ceejayoz Avatar answered Nov 14 '22 21:11

ceejayoz


Also take a look at http_errors option to disable exceptions at all (if for your application it's an expected scenario, and you want to handle all responses specifically by yourself).

like image 25
Alexey Shokov Avatar answered Nov 14 '22 22:11

Alexey Shokov