0

我正在使用 Guzzle 从 API 消费。当该 API 中发生错误时,响应看起来像这样。

Status Code: 500
Content-Type: application/json
-----
{
    error: 'identifier',
    error_messsage: 'foo bar'
}

我希望该正文响应(json 编码)成为 Guzzle 处理的异常中的消息。

try {
    // Below, a Guzzle request
    $request->send();
}
catch ( \Exception $e ) {
    // returns the error response body we talked about before
    $e->getMessage();
}

有没有办法允许这样做?

4

1 回答 1

1

谢谢@dollery,阅读该文档使我找到了解决方案。

使用异常的 getResponse() 方法按预期工作。

try {
    // Below, a Guzzle request
    $request->send();
}
catch ( \Exception $e ) {
    // returns the error response body
    $e->getResponse()->json();
}
于 2014-05-28T13:35:48.140 回答