Created
September 21, 2021 10:18
-
-
Save pounard/eda8df2dcc1cd43180a7efbf4fff7ee0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @see \Symfony\Component\HttpKernel\Controller\ErrorController | |
*/ | |
final class ErrorController | |
{ | |
private bool $debug = false; | |
private ErrorRendererInterface $errorRenderer; | |
private Environment $twig; | |
/** | |
* Default constructor | |
*/ | |
public function __construct(ErrorRendererInterface $errorRenderer, Environment $twig, bool $debug = false) | |
{ | |
$this->debug = $debug; | |
$this->errorRenderer = $errorRenderer; | |
$this->twig = $twig; | |
} | |
/** | |
* Show the error. | |
*/ | |
public function show(Request $request, \Throwable $exception, DebugLoggerInterface $logger = null): Response | |
{ | |
if ($exception instanceof HttpExceptionInterface) { | |
$code = $exception->getStatusCode(); | |
} else { | |
$code = $exception->getCode(); | |
} | |
$template = null; | |
$httpStatusCode = 500; | |
if (403 === $code) { | |
$httpStatusCode = 403; | |
$template = '@gestion/error/error403.html.twig'; | |
} elseif (404 === $code) { | |
$httpStatusCode = 404; | |
$template = '@gestion/error/error404.html.twig'; | |
} elseif (!$this->debug) { | |
$template = '@gestion/error/error.html.twig'; | |
} elseif ('Symfony BrowserKit' === $request->headers->get('User-Agent')) { | |
// Debug mode, et test unitaires, c'est safe de faire ça ici. | |
return new Response( | |
$this->flattenNormalizerExceptionTrace( | |
$this->normalizeExceptionTrace($exception) | |
), | |
$httpStatusCode | |
); | |
} | |
foreach ($request->getAcceptableContentTypes() as $contentType) { | |
// Always let HTML pass. | |
if (false !== \strpos($contentType, 'html')) { | |
break; | |
} | |
if ('application/json' === $contentType) { | |
$responseData = [ | |
'code' => $code, | |
'message' => $exception->getMessage(), | |
]; | |
if ($this->debug) { | |
$responseData['trace'] = $this->normalizeExceptionTrace($exception); | |
} | |
return new JsonResponse($responseData, $httpStatusCode); | |
} | |
} | |
if ($template) { | |
// $this->getAndCleanOutputBuffering($request->headers->get('X-Php-Ob-Level', -1)); | |
return new Response($this->twig->render($template, ['exception' => $exception]), $httpStatusCode); | |
} | |
// Cut and pasted code from \Symfony\Component\HttpKernel\Controller\ErrorController | |
$exception = $this->errorRenderer->render($exception); | |
return new Response($exception->getAsString(), $exception->getStatusCode(), $exception->getHeaders()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment