Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
CRAP
100.00% covered (success)
100.00%
1 / 1
KernelExceptionListener
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
3
100.00% covered (success)
100.00%
1 / 1
 onKernelException
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
3
1<?php
2
3namespace Olz\EventListener;
4
5use Olz\Components\Error\OlzErrorPage\OlzErrorPage;
6use Olz\Utils\WithUtilsTrait;
7use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
8use Symfony\Component\HttpFoundation\Response;
9use Symfony\Component\HttpKernel\Event\ExceptionEvent;
10use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
11
12#[AsEventListener(event: 'kernel.exception', method: 'onKernelException')]
13class KernelExceptionListener {
14    use WithUtilsTrait;
15
16    protected ?\Throwable $is_handling_exception = null;
17
18    public function onKernelException(ExceptionEvent $event): void {
19        $exception = $event->getThrowable();
20        $previous_exception = $this->is_handling_exception;
21        $this->is_handling_exception = $exception;
22
23        if ($previous_exception !== null) {
24            $this->log()->warning("Was already handling exception {$previous_exception->getMessage()}, but now also {$exception->getMessage()}.", [$previous_exception, $exception]);
25            return;
26        }
27
28        $response = new Response();
29
30        if ($exception instanceof HttpExceptionInterface) {
31            $this->log()->info("Handling HttpExceptionInterface {$exception->getMessage()}...", [$exception]);
32            $http_status_code = $exception->getStatusCode();
33            $response->setStatusCode($http_status_code);
34            $response->headers->replace($exception->getHeaders());
35            $response->setContent(OlzErrorPage::render([
36                'http_status_code' => $http_status_code,
37            ], $this));
38        } else {
39            $this->log()->warning("Non-HttpExceptionInterface exception: {$exception->getMessage()}\n{$exception->getTraceAsString()}");
40            $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
41            $response->setContent(OlzErrorPage::render([], $this));
42        }
43
44        $event->setResponse($response);
45    }
46}