Handle Guzzle exception and get HTTP body

前端 未结 6 681
长发绾君心
长发绾君心 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:50

    Guzzle 3.x

    Per the docs, you can catch the appropriate exception type (ClientErrorResponseException for 4xx errors) and call its getResponse() method to get the response object, then call getBody() on that:

    use Guzzle\Http\Exception\ClientErrorResponseException;
    
    ...
    
    try {
        $response = $request->send();
    } catch (ClientErrorResponseException $exception) {
        $responseBody = $exception->getResponse()->getBody(true);
    }
    

    Passing true to the getBody function indicates that you want to get the response body as a string. Otherwise you will get it as instance of class Guzzle\Http\EntityBody.

提交回复
热议问题