Skip to content

Commit

Permalink
Return JsonReponse for /api routes in case of Exceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
y3n4 committed Dec 12, 2024
1 parent 21d767f commit 7d4363f
Show file tree
Hide file tree
Showing 2 changed files with 26 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\ApiExceptionListener:
tags:
- { name: 'kernel.event_listener', event: 'kernel.exception' }

App\Handler\:
resource: '../src/Handler/*'
public: true
Expand Down
22 changes: 22 additions & 0 deletions src/EventListener/ApiExceptionListener.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

namespace App\EventListener;

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

class ApiExceptionListener
{
public function onKernelException(ExceptionEvent $event)
{
$request = $event->getRequest();

if (strpos($request->getPathInfo(), '/api') === 0) {
$exception = $event->getThrowable();
$statusCode = $exception instanceof HttpExceptionInterface ? $exception->getStatusCode() : 500;

$event->setResponse(new JsonResponse(['error' => $exception->getMessage()], $statusCode));
}
}
}

0 comments on commit 7d4363f

Please sign in to comment.