简体   繁体   中英

Guzzle - Access to code on server error

I connecting to API by Guzzle:

$client = new Client();

try {
    $res = $client->post( 'xxx' . $this->url , [
        'headers'   => $headers, 
        'json'      => $data,
    ]);

} catch( Exception $e ) {
    echo json_decode( $e->getResponse()->getBody(), true );
}

And it's working but when it's 'catch', I need to get code from response but I getting:

Server error: `POST XXXXX` resulted in a `555 Error` response: {"status":"ERROR","errors":[{"message":"Subscribers already exists in this subscribers list","code":1304}]}

And I can't get the code. How to do this?

UPDATE
Here is screen with full response.
在此处输入图片说明

Just extract the response from the exception. Guzzle throws a special BadResponseException in case of failure, so take a look at this class.

try {
    // ...
} catch (BadResponseException $exception) {
    // 555
    $exception->getCode();

    $appError = json_decode(
        $exception->getResponse()->getBody()->getContents(),
        true
    );
    // 1304
    $appErrorCode = $appError['errors'][0]['code'];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM