diff --git a/src/EventListener/HtmxExceptionListener.php b/src/EventListener/HtmxExceptionListener.php new file mode 100644 index 0000000..fcc5844 --- /dev/null +++ b/src/EventListener/HtmxExceptionListener.php @@ -0,0 +1,53 @@ + regardless of the original hx-target. + */ +class HtmxExceptionListener implements EventSubscriberInterface +{ + public function __construct(private readonly Environment $twig) + { + } + + public static function getSubscribedEvents(): array + { + return [ + KernelEvents::EXCEPTION => ['onKernelException', -10], + ]; + } + + public function onKernelException(ExceptionEvent $event): void + { + if (false === $event->getRequest()->headers->has('HX-Request')) { + return; + } + + if ($event->hasResponse()) { + return; + } + + $html = $this->twig->render('htmx_error_modal.html.twig'); + + $response = new Response($html, Response::HTTP_OK); + $response->headers->set('HX-Retarget', 'body'); + $response->headers->set('HX-Reswap', 'beforeend'); + + $event->setResponse($response); + $event->allowCustomResponseCode(); + } +} diff --git a/templates/htmx_error_modal.html.twig b/templates/htmx_error_modal.html.twig new file mode 100644 index 0000000..ba78fee --- /dev/null +++ b/templates/htmx_error_modal.html.twig @@ -0,0 +1,12 @@ +{% embed '_partials/_modal.html.twig' with { 'level': 'error' } %} + {% block title %} + Oops... + {% endblock %} + {% block content %} + {% include '_partials/_alert.html.twig' with { + level: 'error', + modal: true, + messages: ['Da ist etwas schiefgelaufen. Wir haben uns Notizen gemacht und kümmern uns schnellstmöglich darum.'] + } %} + {% endblock %} +{% endembed %}