diff --git a/config/services.yaml b/config/services.yaml index a568a500..e2cf9d10 100644 --- a/config/services.yaml +++ b/config/services.yaml @@ -96,6 +96,10 @@ services: $defaultLocale: "%locale%" $supportedLocales: "%supported_locales%" + App\EventListener\JsonExceptionListener: + tags: + - { name: 'kernel.event_listener', event: 'kernel.exception' } + App\Handler\: resource: '../src/Handler/*' public: true diff --git a/src/EventListener/JsonResponseExceptionListener.php b/src/EventListener/JsonResponseExceptionListener.php new file mode 100644 index 00000000..cc698855 --- /dev/null +++ b/src/EventListener/JsonResponseExceptionListener.php @@ -0,0 +1,24 @@ +getRequest(); + + if ( + $request->headers->get('Accept') === 'application/json' || + $request->headers->get('Content-Type') === 'application/json' + ) { + $exception = $event->getThrowable(); + $statusCode = $exception instanceof HttpExceptionInterface ? $exception->getStatusCode() : 500; + $event->setResponse(new JsonResponse(['error' => $exception->getMessage()], $statusCode)); + } + } +}