1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace App\Subscriber; |
4
|
|
|
|
5
|
|
|
use Symfony\Component\EventDispatcher\EventSubscriberInterface; |
6
|
|
|
use Symfony\Component\HttpFoundation\JsonResponse; |
7
|
|
|
use Symfony\Component\HttpFoundation\Response; |
8
|
|
|
use Symfony\Component\HttpKernel\Event\ExceptionEvent; |
9
|
|
|
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; |
10
|
|
|
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface; |
11
|
|
|
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; |
12
|
|
|
use Symfony\Component\HttpKernel\KernelEvents; |
13
|
|
|
|
14
|
|
|
class ApiExceptionSubscriber implements EventSubscriberInterface |
15
|
|
|
{ |
16
|
|
|
public function onKernelException(ExceptionEvent $event): void |
17
|
|
|
{ |
18
|
|
|
$throwable = $event->getThrowable(); |
19
|
|
|
|
20
|
|
|
$response = $this->createResponse($throwable); |
21
|
|
|
|
22
|
|
|
$event->setResponse($response); |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
public static function getSubscribedEvents(): array |
26
|
|
|
{ |
27
|
|
|
return [ |
28
|
|
|
KernelEvents::EXCEPTION => 'onKernelException', |
29
|
|
|
]; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
private function createResponse(\Throwable $throwable): Response |
33
|
|
|
{ |
34
|
|
|
if ($throwable instanceof NotFoundHttpException) { |
35
|
|
|
return new Response( |
36
|
|
|
null, |
37
|
|
|
$throwable->getStatusCode(), |
38
|
|
|
$throwable->getHeaders(), |
39
|
|
|
); |
|
|
|
|
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
if ($throwable instanceof BadRequestHttpException) { |
43
|
|
|
return new JsonResponse( |
44
|
|
|
['errors' => json_decode($throwable->getMessage(), true) ?? [$throwable->getMessage()], ], |
45
|
|
|
$throwable->getStatusCode(), |
46
|
|
|
); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
return new JsonResponse( |
50
|
|
|
['message' => $throwable->getMessage()], |
51
|
|
|
$throwable instanceof HttpExceptionInterface ? $throwable->getStatusCode() : Response::HTTP_INTERNAL_SERVER_ERROR, |
52
|
|
|
); |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
|