【问题标题】:How to keep error response bodies with Guzzle如何使用 Guzzle 保留错误响应主体
【发布时间】:2014-05-28 21:35:48
【问题描述】:

我正在使用 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();
}

有没有办法做到这一点?

【问题讨论】:

标签: php json error-handling response guzzle


【解决方案1】:

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

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

try {
    // Below, a Guzzle request
    $request->send();
}
catch ( \Exception $e ) {
    // returns the error response body
    $e->getResponse()->json();
}

【讨论】:

    猜你喜欢
    • 2019-03-13
    • 1970-01-01
    • 2017-08-26
    • 1970-01-01
    • 2015-02-15
    • 1970-01-01
    • 2021-03-10
    • 2016-04-26
    • 1970-01-01
    相关资源
    最近更新 更多