Php Guzzle-访问服务器上的代码错误
I通过Guzzle连接到API:Php Guzzle-访问服务器上的代码错误,php,request,guzzle,Php,Request,Guzzle,I通过Guzzle连接到API: $client = new Client(); try { $res = $client->post( 'xxx' . $this->url , [ 'headers' => $headers, 'json' => $data, ]); } catch( Exception $e ) { echo json_decode( $e->getResponse()
$client = new Client();
try {
$res = $client->post( 'xxx' . $this->url , [
'headers' => $headers,
'json' => $data,
]);
} catch( Exception $e ) {
echo json_decode( $e->getResponse()->getBody(), true );
}
它正在工作,但当它是“catch”时,我需要从响应中获取代码,但我得到:
Server error: `POST XXXXX` resulted in a `555 Error` response: {"status":"ERROR","errors":[{"message":"Subscribers already exists in this subscribers list","code":1304}]}
而我却找不到密码。如何做到这一点
更新这是完整响应的屏幕。
只需从异常中提取响应即可。Guzzle在失败的情况下抛出一个特殊的值,所以看看这个类
try {
// ...
} catch (BadResponseException $exception) {
// 555
$exception->getCode();
$appError = json_decode(
$exception->getResponse()->getBody()->getContents(),
true
);
// 1304
$appErrorCode = $appError['errors'][0]['code'];
}
你是说异常代码吗?或者HTTP返回状态代码?@AlexHowansky HTTP。此代码->
“code”:1304
您必须查看服务器上运行的任何软件的文档,最后请注意->getContents()
。我希望您已经了解了这一点——异常包含响应,您可以像处理普通响应(提取JSON等)一样使用它。