<?php 
 
namespace ApiBundle\Exceptions; 
 
use PDOException; 
use Symfony\Component\HttpFoundation\JsonResponse; 
use Symfony\Component\HttpKernel\Event\ExceptionEvent; 
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; 
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface; 
 
class ExceptionListener 
{ 
    public function onKernelException(ExceptionEvent $event) 
    { 
        $exception = $event->getThrowable(); 
        $request = $event->getRequest(); 
 
        $controller = $request->attributes->get('_controller'); 
 
        if ($controller && strpos($controller, 'ApiBundle\\Controller\\') !== 0) { 
            return; 
        } 
 
        $statusCode = 500; 
        $data = [ 
            'success' => false, 
            'message' => 'Internal server error', 
        ]; 
 
        if ($exception instanceof HttpExceptionInterface) { 
            $statusCode = $exception->getStatusCode(); 
            $data['message'] = $exception->getMessage(); 
        } 
 
        if ($exception instanceof PDOException) { 
            $statusCode = 500; 
            $data['message'] = 'Database error'; 
        } 
 
        if ($exception instanceof BadRequestHttpException) { 
            $statusCode = 422; 
 
            $decoded = json_decode($exception->getMessage(), true); 
 
            if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) { 
                $data['message'] = 'Validation error'; 
                $data['errors'] = $decoded; 
            } else { 
                $data['message'] = $exception->getMessage(); 
            } 
        } 
 
        if ($request->query->get('debug') === 'true') { 
            $data['error'] = $exception->getMessage(); 
            $data['trace'] = $exception->getTraceAsString(); 
        } 
 
        $response = new JsonResponse($data, $statusCode); 
        $event->setResponse($response); 
    } 
}