2
votes

I'm looking for a modern (Laravel 5.4) way to display custom 500 error page only for HTTP (non ajax/fetch) response. I read some threads but each response looks like a trick or is outdated. There is probably something to modify in \App\Exceptions\Handler, but I did not find the "right way".

Is there a simple way to display a specific page on fatal error (uncatched, returning 500) in Laravel 5.4?

In other words, when I have a syntax error on one of my controller, it displays "Whoops something went wrong" with some HTML and 500 error code. I would like to display something else, with the same rules as default behavior (ideally only for HTML browser, not for ajax/fetch, etc.).

EDIT: only in production environment.

3

3 Answers

2
votes

Laravel makes it easy to display custom error pages for various HTTP status codes. For example, if you wish to customize the error page for 404 HTTP status codes, create a resources/views/errors/404.blade.php. This file will be served on all 404 errors generated by your application. The views within this directory should be named to match the HTTP status code they correspond to. The HttpException instance raised by the abort function will be passed to the view as an $exception variable.

https://laravel.com/docs/5.4/errors#custom-http-error-pages

0
votes

From the selected "best answer" of this thread: https://laracasts.com/discuss/channels/general-discussion/custom-error-page-er500

You could modify \App\Exceptions\Handler::render():

public function render($request, Exception $exception)
{
    if (config('app.debug') && !$this->isHttpException($exception)) {
        $exception = new \Symfony\Component\HttpKernel\Exception\HttpException(500);
    }
    return parent::render($request, $exception);
}

Your exception will be reported in the logs as usually, but woops page will be replaced by your 500.blade.php view.

0
votes

Sometimes you have to catch the specific exception in order to render the error view. in Laravel 5.4 you can do this by editing the report() method in the App\Exceptions\Handler class

public function report(Exception $exception)
{
    if ($exception instanceof CustomException) {
        // here you can log the error and return the view, redirect, etc...
    }

    return parent::report($exception);
}