Skip to content

Commit ead0074

Browse files
authored
Merge pull request #141 from rbibby/master
Handle API Gateway errors as part of ApiException
2 parents ac11527 + a193a69 commit ead0074

File tree

2 files changed

+33
-7
lines changed

2 files changed

+33
-7
lines changed

src/Exception/ApiException.php

+14-6
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
$raw = $response->getBody()->getContents();
1719
$body = json_decode($raw);
1820
$err = json_last_error();
@@ -22,6 +24,8 @@ public function __construct($response)
2224

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

2731
if (!empty($this->errors)) {
@@ -32,12 +36,6 @@ public function __construct($response)
3236

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

4341
/**
@@ -86,4 +84,14 @@ private function getErrorsFromBody($body)
8684

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

tests/ApiExceptionTest.php

+19-1
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)