From b781150ee91f21f8c9ce16630116ea2db9afc5ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20B=C3=B6hmer?= Date: Sun, 10 Mar 2024 00:12:54 +0100 Subject: [PATCH] Show the error page in a pop up in prod environment too --- .../ErrorHandling/FixedErrorController.php | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 src/Controller/ErrorHandling/FixedErrorController.php diff --git a/src/Controller/ErrorHandling/FixedErrorController.php b/src/Controller/ErrorHandling/FixedErrorController.php new file mode 100644 index 00000000..610a07b1 --- /dev/null +++ b/src/Controller/ErrorHandling/FixedErrorController.php @@ -0,0 +1,64 @@ +. + */ + +declare(strict_types=1); + + +namespace App\Controller\ErrorHandling; + +use Symfony\Component\DependencyInjection\Attribute\AsDecorator; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\Controller\ErrorController; + +/** + * This class decorates the default error decorator and changes the content type of responses, if it went through a + * Turbo request. + * The problem is, that the default error controller returns in the format of the preferred content type of the request. + * This is turbo-stream. This causes Turbo to try to integrate it into the content frame and not trigger the ajax failed + * events to show the error in a popup like intended. + */ +#[AsDecorator("error_controller")] +class FixedErrorController +{ + public function __construct(private readonly ErrorController $decorated) + {} + + public function __invoke(\Throwable $exception): Response + { + $response = ($this->decorated)($exception); + + //Check the content type of the response + $contentType = $response->headers->get('Content-Type'); + + //If the content type is turbo stream, change the content type to html + //This prevents Turbo to render the response as a turbo stream, and forces to render it in the popup + if ($contentType === 'text/vnd.turbo-stream.html') { + $response->headers->set('Content-Type', 'text/html'); + } + + return $response; + } + + public function preview(Request $request, int $code): Response + { + return ($this->decorated)->preview($request, $code); + } +} \ No newline at end of file