Issues (15)

src/EventSubscriber/ApiExceptionSubscriber.php (1 issue)

1
<?php
2
3
namespace App\EventSubscriber;
4
5
use SWP\Component\Common\Exception\HttpException;
6
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
7
use Symfony\Component\HttpFoundation\JsonResponse;
8
use Symfony\Component\HttpFoundation\Response;
9
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
10
use Symfony\Component\HttpKernel\Exception\HttpException as SymfonyHttpException;
11
12
class ApiExceptionSubscriber implements EventSubscriberInterface
13
{
14
    public function onExceptionEvent(ExceptionEvent $event)
15
    {
16
        $request = $event->getRequest();
17
        $exception = $event->getException();
0 ignored issues
show
Deprecated Code introduced by
The function Symfony\Component\HttpKe...onEvent::getException() has been deprecated: since Symfony 4.4, use getThrowable instead ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

17
        $exception = /** @scrutinizer ignore-deprecated */ $event->getException();

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
18
        if ('application/json' === $request->headers->get('Content-Type')) {
19
            $code = Response::HTTP_INTERNAL_SERVER_ERROR;
20
            if ($exception instanceof HttpException) {
21
                $code = $exception->getStatusCode();
22
            }
23
24
            if ($exception instanceof SymfonyHttpException) {
25
                $code = $exception->getPrevious()->getCode();
26
            }
27
28
            $event->setResponse(new JsonResponse([
29
                'success' => false,
30
                'message' => $exception->getMessage(),
31
            ], $code));
32
        }
33
    }
34
35
    public static function getSubscribedEvents()
36
    {
37
        return [
38
            ExceptionEvent::class => 'onExceptionEvent',
39
        ];
40
    }
41
}
42