src/ApiBundle/Exceptions/ExceptionListener.php line 13

Open in your IDE?
  1. <?php
  2. namespace ApiBundle\Exceptions;
  3. use PDOException;
  4. use Symfony\Component\HttpFoundation\JsonResponse;
  5. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  6. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  7. use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
  8. class ExceptionListener
  9. {
  10.     public function onKernelException(ExceptionEvent $event)
  11.     {
  12.         $exception $event->getThrowable();
  13.         $request $event->getRequest();
  14.         $controller $request->attributes->get('_controller');
  15.         if ($controller && strpos($controller'ApiBundle\\Controller\\') !== 0) {
  16.             return;
  17.         }
  18.         $statusCode 500;
  19.         $data = [
  20.             'success' => false,
  21.             'message' => 'Internal server error',
  22.         ];
  23.         if ($exception instanceof HttpExceptionInterface) {
  24.             $statusCode $exception->getStatusCode();
  25.             $data['message'] = $exception->getMessage();
  26.         }
  27.         if ($exception instanceof PDOException) {
  28.             $statusCode 500;
  29.             $data['message'] = 'Database error';
  30.         }
  31.         if ($exception instanceof BadRequestHttpException) {
  32.             $statusCode 422;
  33.             $decoded json_decode($exception->getMessage(), true);
  34.             if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
  35.                 $data['message'] = 'Validation error';
  36.                 $data['errors'] = $decoded;
  37.             } else {
  38.                 $data['message'] = $exception->getMessage();
  39.             }
  40.         }
  41.         if ($request->query->get('debug') === 'true') {
  42.             $data['error'] = $exception->getMessage();
  43.             $data['trace'] = $exception->getTraceAsString();
  44.         }
  45.         $response = new JsonResponse($data$statusCode);
  46.         $event->setResponse($response);
  47.     }
  48. }