Skip to content

Commit c12a2a6

Browse files
committed
Add method to get Request-ID header from ApiException
1 parent 5ded87f commit c12a2a6

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

src/Exception/ApiException.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,11 @@ class ApiException extends UKFastException
1010

1111
protected $response;
1212

13+
/**
14+
* @var string
15+
*/
16+
protected $requestId = null;
17+
1318
public function __construct($response)
1419
{
1520
$response->getBody()->rewind();
@@ -32,6 +37,10 @@ public function __construct($response)
3237
$this->message = $message;
3338
}
3439

40+
if (!empty($response->getHeader('Request-ID')[0])) {
41+
$this->requestId = $response->getHeader('Request-ID')[0];
42+
}
43+
3544
$this->response = $response;
3645
}
3746

@@ -59,6 +68,11 @@ public function getResponse()
5968
return $this->response;
6069
}
6170

71+
public function getRequestId()
72+
{
73+
return $this->requestId;
74+
}
75+
6276
private function getErrorsFromBody($body)
6377
{
6478
$errors = [];

tests/ApiExceptionTest.php

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,10 @@ class ApiExceptionTest extends TestCase
1414
*/
1515
public function constructs_from_standard_api_error()
1616
{
17-
$response = new Response(500, [], json_encode([
17+
$headers = [
18+
'Request-ID' => 'test-request-id',
19+
];
20+
$response = new Response(500, $headers, json_encode([
1821
'errors' => [
1922
[
2023
'detail' => 'Test'
@@ -26,6 +29,7 @@ public function constructs_from_standard_api_error()
2629

2730
$this->assertEquals(1, count($exception->getErrors()));
2831
$this->assertEquals('Test', $exception->getErrors()[0]->detail);
32+
$this->assertEquals('test-request-id', $exception->getRequestId());
2933
}
3034

3135
/**
@@ -54,4 +58,22 @@ public function throws_invalid_json_exception_when_given_bad_json()
5458
$this->expectException(InvalidJsonException::class);
5559
$exception = new ApiException($response);
5660
}
61+
62+
/**
63+
* @test
64+
*/
65+
public function request_id_is_set_to_null_if_none_is_returned()
66+
{
67+
$response = new Response(500, [], json_encode([
68+
'errors' => [
69+
[
70+
'detail' => 'Test'
71+
]
72+
]
73+
]));
74+
75+
$exception = new ApiException($response);
76+
77+
$this->assertNull($exception->getRequestId());
78+
}
5779
}

0 commit comments

Comments
 (0)