Skip to content

Commit 5fe240d

Browse files
committed
Add Exception Event Listener
1 parent c8626cf commit 5fe240d

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

EventListener/ExceptionListener.php

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
<?php
2+
3+
namespace TheCodingMachine\GraphQLite\Bundle\EventListener;
4+
5+
use GraphQL\Error\Error;
6+
use GraphQL\Executor\ExecutionResult;
7+
use Symfony\Component\HttpFoundation\JsonResponse;
8+
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
9+
use TheCodingMachine\GraphQLite\Exceptions\GraphQLExceptionInterface;
10+
use TheCodingMachine\GraphQLite\Http\HttpCodeDecider;
11+
use TheCodingMachine\GraphQLite\Http\HttpCodeDeciderInterface;
12+
13+
class ExceptionListener
14+
{
15+
private readonly HttpCodeDeciderInterface $httpCodeDecider;
16+
17+
public function __construct(
18+
?HttpCodeDeciderInterface $httpCodeDecider = null,
19+
) {
20+
$this->httpCodeDecider = $httpCodeDecider ?? new HttpCodeDecider();
21+
}
22+
23+
public function onKernelException(ExceptionEvent $event): void
24+
{
25+
$exception = $event->getThrowable();
26+
27+
if ($exception instanceof GraphQLExceptionInterface) {
28+
$result = new ExecutionResult(
29+
errors: [new Error(
30+
message: $exception->getMessage(),
31+
previous: $exception,
32+
extensions: $exception->getExtensions()
33+
)]
34+
);
35+
36+
$response = new JsonResponse($result->toArray(), $this->httpCodeDecider->decideHttpStatusCode($result));
37+
38+
$event->setResponse($response);
39+
}
40+
}
41+
}

src/Resources/config/container/graphqlite.xml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,10 @@
8787
<tag name="routing.route_loader"/>
8888
</service>
8989

90+
<service id="TheCodingMachine\GraphQLite\Bundle\EventListener\ExceptionListener">
91+
<tag name="kernel.event_listener" event="kernel.exception" method="onKernelException" />
92+
</service>
93+
9094
<service id="TheCodingMachine\GraphQLite\Bundle\Mappers\RequestParameterMiddleware">
9195
<tag name="graphql.parameter_middleware"/>
9296
</service>

0 commit comments

Comments
 (0)