diff --git a/src/Exception/ApiException.php b/src/Exception/ApiException.php index 5466171a..3bcb8599 100644 --- a/src/Exception/ApiException.php +++ b/src/Exception/ApiException.php @@ -13,6 +13,8 @@ class ApiException extends UKFastException public function __construct($response) { $response->getBody()->rewind(); + $this->response = $response; + $raw = $response->getBody()->getContents(); $body = json_decode($raw); $err = json_last_error(); @@ -22,6 +24,8 @@ public function __construct($response) if (isset($body->errors) && is_array($body->errors)) { $this->errors = $this->getErrorsFromBody($body); + } elseif (isset($body->message)) { + $this->errors = $this->getApiGatewayErrorFromBody($body); } if (!empty($this->errors)) { @@ -32,12 +36,6 @@ public function __construct($response) $this->message = $message; } - - if (!empty($response->getHeader('Request-ID')[0])) { - $this->requestId = $response->getHeader('Request-ID')[0]; - } - - $this->response = $response; } /** @@ -86,4 +84,14 @@ private function getErrorsFromBody($body) return $errors; } + + private function getApiGatewayErrorFromBody($body) + { + $error = new ApiError; + $error->title = 'API Gateway Error'; + $error->detail = $body->message; + $error->status = $this->response->getStatusCode(); + + return [$error]; + } } diff --git a/tests/ApiExceptionTest.php b/tests/ApiExceptionTest.php index f0f47e57..1eb2a340 100644 --- a/tests/ApiExceptionTest.php +++ b/tests/ApiExceptionTest.php @@ -32,6 +32,24 @@ public function constructs_from_standard_api_error() $this->assertEquals('test-request-id', $exception->getRequestId()); } + /** + * @test + */ + public function constructs_from_api_gateway_error() + { + $response = new Response(401, [], json_encode([ + 'message' => 'Invalid authentication credentials' + ])); + + $exception = new ApiException($response); + + $this->assertEquals(1, count($exception->getErrors())); + $this->assertEquals('API Gateway Error', $exception->getErrors()[0]->title); + $this->assertEquals('Invalid authentication credentials', $exception->getErrors()[0]->detail); + $this->assertEquals(401, $exception->getErrors()[0]->status); + } + + /** * @test */ @@ -62,7 +80,7 @@ public function throws_invalid_json_exception_when_given_bad_json() /** * @test */ - public function request_id_is_set_to_null_if_none_is_returned() + public function request_id_is_null_if_none_is_returned() { $response = new Response(500, [], json_encode([ 'errors' => [