Skip to content

Commit d329ad4

Browse files
authored
Merge pull request #32 from 5am-code/feature/enhance-notion-exception
enhanced notion exception by detailed response message
2 parents 367cd32 + e9ec077 commit d329ad4

File tree

3 files changed

+56
-1
lines changed

3 files changed

+56
-1
lines changed

src/Exceptions/NotionException.php

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace FiveamCode\LaravelNotionApi\Exceptions;
44

55
use Illuminate\Http\Client\Response;
6+
use Throwable;
67

78
/**
89
* Class NotionException
@@ -33,8 +34,22 @@ public static function instance(string $message, array $payload = []): NotionExc
3334
*/
3435
public static function fromResponse(Response $response): NotionException
3536
{
37+
$responseBody = json_decode($response->getBody()->getContents(), true);
38+
39+
$errorCode = $errorMessage = "";
40+
if (array_key_exists("code", $responseBody)) {
41+
$errorCode = "({$responseBody["code"]})";
42+
}
43+
44+
if (array_key_exists("code", $responseBody)) {
45+
$errorMessage = "({$responseBody["message"]})";
46+
}
47+
48+
$message = "{$response->getReasonPhrase()}: {$errorCode} {$errorMessage}";
49+
3650
return new NotionException(
37-
$response->getReasonPhrase(), 0,
51+
$message,
52+
0,
3853
$response->toException()
3954
);
4055
}

tests/NotionExceptionTest.php

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
<?php
2+
3+
namespace FiveamCode\LaravelNotionApi\Tests;
4+
5+
use FiveamCode\LaravelNotionApi\Exceptions\NotionException;
6+
use Notion;
7+
use Illuminate\Support\Facades\Http;
8+
9+
/**
10+
* Class HandlingExceptionTest
11+
* @package FiveamCode\LaravelNotionApi\Tests
12+
*/
13+
class NotionExceptionTest extends NotionApiTest
14+
{
15+
16+
/** @test */
17+
public function it_throws_a_notion_exception_with_detailed_message_from_response()
18+
{
19+
20+
Http::fake([
21+
'https://api.notion.com/v1/blocks/d092140ce4e549bf9915fb8ad43d1699d/children*'
22+
=> Http::response(
23+
json_decode(file_get_contents("tests/stubs/endpoints/blocks/response_children_invalid_uuid_400.json"), true),
24+
400,
25+
['Headers']
26+
)
27+
]);
28+
29+
$this->expectException(NotionException::class);
30+
$this->expectExceptionMessage("Bad Request: (validation_error) (path failed validation: path.id should be a valid uuid, instead was");
31+
32+
\Notion::block("d092140ce4e549bf9915fb8ad43d1699d")->children()->asCollection();
33+
}
34+
}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"object": "error",
3+
"status": 400,
4+
"code": "validation_error",
5+
"message": "path failed validation: path.id should be a valid uuid, instead was `\"d092140ce4e549bf9915fb8ad43d1699d\"`."
6+
}

0 commit comments

Comments
 (0)