Skip to content

Commit

Permalink
Merge pull request #141 from rbibby/master
Browse files Browse the repository at this point in the history
Handle API Gateway errors as part of ApiException
  • Loading branch information
bluemorbo authored Nov 13, 2019
2 parents ac11527 + a193a69 commit ead0074
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 7 deletions.
20 changes: 14 additions & 6 deletions src/Exception/ApiException.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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)) {
Expand All @@ -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;
}

/**
Expand Down Expand Up @@ -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];
}
}
20 changes: 19 additions & 1 deletion tests/ApiExceptionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
*/
Expand Down Expand Up @@ -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' => [
Expand Down

0 comments on commit ead0074

Please sign in to comment.