Handle Guzzle exception and get HTTP body

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

    None of the above responses are working for error that has no body but still has some describing text. For me, it was SSL certificate problem: unable to get local issuer certificate error. So I looked right into the code, because doc does't really say much, and did this (in Guzzle 7.1):

    try {
        // call here
    } catch (\GuzzleHttp\Exception\RequestException $e) {
        if ($e->hasResponse()) {
            $response = $e->getResponse();
            // message is in $response->getReasonPhrase()
        } else {
            $response = $e->getHandlerContext();
            if (isset($response['error'])) {
                // message is in $response['error']
            } else {
                // Unknown error occured!
            }
        }
    }
    

提交回复
热议问题