Skip to content

Commit

Permalink
Return Exceptions as JSON reponse for JSON request
Browse files Browse the repository at this point in the history
  • Loading branch information
y3n4 committed Dec 12, 2024
1 parent 21d767f commit e7000f6
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
4 changes: 4 additions & 0 deletions config/services.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
24 changes: 24 additions & 0 deletions src/EventListener/JsonResponseExceptionListener.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

namespace App\EventListener;

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;

class JsonResponseExceptionListener
{
public function onKernelException(ExceptionEvent $event)
{
$request = $event->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));
}
}
}

0 comments on commit e7000f6

Please sign in to comment.