Skip to content

Commit 937fd6e

Browse files
committed
Handle API Gateway errors as part of ApiException
1 parent e158375 commit 937fd6e

File tree

2 files changed

+33
-7
lines changed

2 files changed

+33
-7
lines changed

src/Exception/ApiException.php

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ class ApiException extends UKFastException
1313
public function __construct($response)
1414
{
1515
$response->getBody()->rewind();
16+
$this->response = $response;
17+
1618
$body = json_decode($response->getBody()->getContents());
1719
$err = json_last_error();
1820
if ($err !== JSON_ERROR_NONE) {
@@ -21,6 +23,8 @@ public function __construct($response)
2123

2224
if (isset($body->errors) && is_array($body->errors)) {
2325
$this->errors = $this->getErrorsFromBody($body);
26+
} elseif (isset($body->message)) {
27+
$this->errors = $this->getApiGatewayErrorFromBody($body);
2428
}
2529

2630
if (!empty($this->errors)) {
@@ -31,12 +35,6 @@ public function __construct($response)
3135

3236
$this->message = $message;
3337
}
34-
35-
if (!empty($response->getHeader('Request-ID')[0])) {
36-
$this->requestId = $response->getHeader('Request-ID')[0];
37-
}
38-
39-
$this->response = $response;
4038
}
4139

4240
/**
@@ -85,4 +83,14 @@ private function getErrorsFromBody($body)
8583

8684
return $errors;
8785
}
86+
87+
private function getApiGatewayErrorFromBody($body)
88+
{
89+
$error = new ApiError;
90+
$error->title = 'API Gateway Error';
91+
$error->detail = $body->message;
92+
$error->status = $this->response->getStatusCode();
93+
94+
return [$error];
95+
}
8896
}

tests/ApiExceptionTest.php

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,24 @@ public function constructs_from_standard_api_error()
3232
$this->assertEquals('test-request-id', $exception->getRequestId());
3333
}
3434

35+
/**
36+
* @test
37+
*/
38+
public function constructs_from_api_gateway_error()
39+
{
40+
$response = new Response(401, [], json_encode([
41+
'message' => 'Invalid authentication credentials'
42+
]));
43+
44+
$exception = new ApiException($response);
45+
46+
$this->assertEquals(1, count($exception->getErrors()));
47+
$this->assertEquals('API Gateway Error', $exception->getErrors()[0]->title);
48+
$this->assertEquals('Invalid authentication credentials', $exception->getErrors()[0]->detail);
49+
$this->assertEquals(401, $exception->getErrors()[0]->status);
50+
}
51+
52+
3553
/**
3654
* @test
3755
*/
@@ -62,7 +80,7 @@ public function throws_invalid_json_exception_when_given_bad_json()
6280
/**
6381
* @test
6482
*/
65-
public function request_id_is_set_to_null_if_none_is_returned()
83+
public function request_id_is_null_if_none_is_returned()
6684
{
6785
$response = new Response(500, [], json_encode([
6886
'errors' => [

0 commit comments

Comments
 (0)