Handle Guzzle exception and get HTTP body

前端 未结 6 694
长发绾君心
长发绾君心 2020-12-07 08:32

I would like to handle errors from Guzzle when the server returns 4xx and 5xx status codes. I make a request like this:

$client = $this->getGuzzleClient()         


        
6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-07 08:42

    Guzzle 6.x

    Per the docs, the exception types you may need to catch are:

    • GuzzleHttp\Exception\ClientException for 400-level errors
    • GuzzleHttp\Exception\ServerException for 500-level errors
    • GuzzleHttp\Exception\BadResponseException for both (it's their superclass)

    Code to handle such errors thus now looks something like this:

    $client = new GuzzleHttp\Client;
    try {
        $client->get('http://google.com/nosuchpage');    
    }
    catch (GuzzleHttp\Exception\ClientException $e) {
        $response = $e->getResponse();
        $responseBodyAsString = $response->getBody()->getContents();
    }
    

提交回复
热议问题