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

守給你的承諾、 提交于 2019-12-06 04:53:21

问题


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

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

I just want my application to continue running and loading.


回答1:


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.




回答2:


I would try something like this:

public static function get($url) {


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

        }
      report($e);
      return false;
    }

}

The report() helper function allows you to quickly report an exception using your exception handler's report method without rendering an error page.




回答3:


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




回答4:


You can catch any exception with this :

catch (\Exception $e)



回答5:


Instead of using just ClientException

You can try RequestException, which will help to handle bad requests.

try {
    // Your code here. 
} catch (GuzzleHttp\Exception\RequestException $e) {
    if ($e->hasResponse()) {
        // Get response body
        // Modify message as proper response
        $message = $e->getResponse()->getBody();
        return (string) $exception;
     }
    else {
        return $e->getMessage();
    }
}


来源:https://stackoverflow.com/questions/46817723/how-to-prevent-crashing-when-guzzle-detect-400-or-500-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!