Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Return GraphQL JSON response in case of JSON Input error instead of Internal Server Error #208

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 19 additions & 5 deletions Controller/GraphQLiteController.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
use TheCodingMachine\GraphQLite\Bundle\Context\SymfonyGraphQLContext;
use TheCodingMachine\GraphQLite\Bundle\Exceptions\JsonException;

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

if (strtoupper($request->getMethod()) === "POST" && empty($psr7Request->getParsedBody())) {
$content = $psr7Request->getBody()->getContents();
$parsedBody = json_decode($content, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new \RuntimeException('Invalid JSON received in POST body: '.json_last_error_msg());
try {
$parsedBody = json_decode(
json: $content,
associative: true,
flags: \JSON_THROW_ON_ERROR
);
} catch (\JsonException $e) {
throw JsonException::create(
reason: $e->getMessage(),
code: Response::HTTP_UNSUPPORTED_MEDIA_TYPE,
previous:$e
);
}
if (!is_array($parsedBody)){
throw new \RuntimeException('Expecting associative array from request, got ' . gettype($parsedBody));

if (!is_array($parsedBody)) {
throw JsonException::create(
reason: 'Expecting associative array from request, got ' . gettype($parsedBody),
code: Response::HTTP_UNPROCESSABLE_ENTITY
);
}
$psr7Request = $psr7Request->withParsedBody($parsedBody);
}
Expand Down
2 changes: 1 addition & 1 deletion DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ class Configuration implements ConfigurationInterface
/**
* @return TreeBuilder
*/
public function getConfigTreeBuilder()
public function getConfigTreeBuilder(): TreeBuilder
{
$treeBuilder = new TreeBuilder('graphqlite');
$rootNode = $treeBuilder->getRootNode();
Expand Down
41 changes: 41 additions & 0 deletions EventListener/ExceptionListener.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

namespace TheCodingMachine\GraphQLite\Bundle\EventListener;

use GraphQL\Error\Error;
use GraphQL\Executor\ExecutionResult;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use TheCodingMachine\GraphQLite\Exceptions\GraphQLExceptionInterface;
use TheCodingMachine\GraphQLite\Http\HttpCodeDecider;
use TheCodingMachine\GraphQLite\Http\HttpCodeDeciderInterface;

class ExceptionListener
{
private readonly HttpCodeDeciderInterface $httpCodeDecider;

public function __construct(
?HttpCodeDeciderInterface $httpCodeDecider = null,
) {
$this->httpCodeDecider = $httpCodeDecider ?? new HttpCodeDecider();
}

public function onKernelException(ExceptionEvent $event): void
{
$exception = $event->getThrowable();

if ($exception instanceof GraphQLExceptionInterface) {
$result = new ExecutionResult(
errors: [new Error(
message: $exception->getMessage(),
previous: $exception,
extensions: $exception->getExtensions()
)]
);

$response = new JsonResponse($result->toArray(), $this->httpCodeDecider->decideHttpStatusCode($result));

$event->setResponse($response);
}
}
}
19 changes: 19 additions & 0 deletions Exceptions/JsonException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

namespace TheCodingMachine\GraphQLite\Bundle\Exceptions;

use Exception;
use TheCodingMachine\GraphQLite\Exceptions\GraphQLException;

class JsonException extends GraphQLException
{
public static function create(?string $reason = null, int $code = 400, Exception $previous = null): self
{
return new self(
message: 'Invalid JSON.',
code: $code,
previous: $previous,
extensions: ['reason' => $reason]
);
}
}
4 changes: 4 additions & 0 deletions Resources/config/container/graphqlite.xml
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,10 @@
<tag name="routing.route_loader"/>
</service>

<service id="TheCodingMachine\GraphQLite\Bundle\EventListener\ExceptionListener">
<tag name="kernel.event_listener" event="kernel.exception" method="onKernelException" />
</service>

<service id="TheCodingMachine\GraphQLite\Bundle\Mappers\RequestParameterMiddleware">
<tag name="graphql.parameter_middleware"/>
</service>
Expand Down
22 changes: 22 additions & 0 deletions Tests/FunctionalTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,28 @@ public function testErrors(): void
$kernel = new GraphQLiteTestingKernel();
$kernel->boot();

$request = Request::create('/graphql', 'POST', [], [], [], ['CONTENT_TYPE' => 'application/json'], '{"query":"{ invalidJsonSyntax }"');

$response = $kernel->handle($request);

$this->assertSame(415, $response->getStatusCode());

$result = json_decode($response->getContent(), true);

$this->assertSame('Invalid JSON.', $result['errors'][0]['message']);
$this->assertSame('Syntax error', $result['errors'][0]['extensions']['reason']);

$request = Request::create('/graphql', 'POST', [], [], [], ['CONTENT_TYPE' => 'application/json'], '"Unexpected Json Content"');

$response = $kernel->handle($request);

$this->assertSame(422, $response->getStatusCode());

$result = json_decode($response->getContent(), true);

$this->assertSame('Invalid JSON.', $result['errors'][0]['message']);
$this->assertSame('Expecting associative array from request, got string', $result['errors'][0]['extensions']['reason']);

$request = Request::create('/graphql', 'GET', ['query' => '
{
notExists
Expand Down
Loading