我正在使用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();
}
有没有办法做到这一点?
最佳答案
感谢@dollery,阅读了该文档后,我找到了解决方案。
使用异常的getResponse()方法可以按预期工作。
try {
// Below, a Guzzle request
$request->send();
}
catch ( \Exception $e ) {
// returns the error response body
$e->getResponse()->json();
}
关于php - 如何使用Guzzle保留错误响应主体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23892173/