Skip to content

Commit 8611016

Browse files
committed
Throw GraphQLException in case of JSON syntax error
1 parent 5fe240d commit 8611016

File tree

2 files changed

+38
-5
lines changed

2 files changed

+38
-5
lines changed

Exceptions/JsonException.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<?php
2+
3+
namespace TheCodingMachine\GraphQLite\Bundle\Exceptions;
4+
5+
use Exception;
6+
use TheCodingMachine\GraphQLite\Exceptions\GraphQLException;
7+
8+
class JsonException extends GraphQLException
9+
{
10+
public static function create(?string $reason = null, int $code = 400, Exception $previous = null): self
11+
{
12+
return new self(
13+
message: 'Invalid JSON.',
14+
code: $code,
15+
previous: $previous,
16+
extensions: ['reason' => $reason]
17+
);
18+
}
19+
}

src/Controller/GraphQLiteController.php

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
use function array_map;
2828
use function class_exists;
2929
use function json_decode;
30+
use TheCodingMachine\GraphQLite\Bundle\Exceptions\JsonException;
3031

3132
/**
3233
* Listens to every single request and forward Graphql requests to Graphql Webonix standardServer.
@@ -80,12 +81,25 @@ public function handleRequest(Request $request): Response
8081

8182
if (strtoupper($request->getMethod()) === 'POST' && empty($psr7Request->getParsedBody())) {
8283
$content = $psr7Request->getBody()->getContents();
83-
$parsedBody = json_decode($content, true);
84-
if (json_last_error() !== JSON_ERROR_NONE) {
85-
throw new \RuntimeException('Invalid JSON received in POST body: '.json_last_error_msg());
84+
try {
85+
$parsedBody = json_decode(
86+
json: $content,
87+
associative: true,
88+
flags: \JSON_THROW_ON_ERROR
89+
);
90+
} catch (\JsonException $e) {
91+
throw JsonException::create(
92+
reason: $e->getMessage(),
93+
code: Response::HTTP_UNSUPPORTED_MEDIA_TYPE,
94+
previous:$e
95+
);
8696
}
87-
if (!is_array($parsedBody)){
88-
throw new \RuntimeException('Expecting associative array from request, got ' . gettype($parsedBody));
97+
98+
if (!is_array($parsedBody)) {
99+
throw JsonException::create(
100+
reason: 'Expecting associative array from request, got ' . gettype($parsedBody),
101+
code: Response::HTTP_UNPROCESSABLE_ENTITY
102+
);
89103
}
90104
$psr7Request = $psr7Request->withParsedBody($parsedBody);
91105
}

0 commit comments

Comments
 (0)