Skip to content

Instantly share code, notes, and snippets.

@pounard
Created September 21, 2021 10:18
Show Gist options
  • Save pounard/eda8df2dcc1cd43180a7efbf4fff7ee0 to your computer and use it in GitHub Desktop.
Save pounard/eda8df2dcc1cd43180a7efbf4fff7ee0 to your computer and use it in GitHub Desktop.
/**
* @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