Home > Net >  Make all error status codes return a single custom view
Make all error status codes return a single custom view

Time:02-01

By default, Laravel looks for error views under resources/views/errors, returning the corresponding view for the relevant status code, eg. 404 or 403. Instead of creating all these views manually I want to use my own custom view for all error codes, with the actual error code and message shown dynamically in the view using getMessage() and any other helper functions that might be available to me.

This would allow me to do this as normal:

abort(<statuscode>, <mymessage>)

...but always return just the one view.

Note that what I'm asking is not the same as what's being requested here, which is to force all errors to 404s no matter their actual status code. I want to keep status codes as they should be, just render them all in the same view.

CodePudding user response:

In the default exception handler, a method called getHttpExceptionView() determines the view to return. Simply override it in your App\Exceptions\Handler class with your desired logic.

use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;

protected function getHttpExceptionView($e)
{
    if ($e->getStatusCode() === 409) {
        return "exceptions.special";
    }
    return "exceptions.default";
}

You're returning a standard view path, dot-separated if you are using directories.

CodePudding user response:

As outlined by miken32's answer, I added the following to the bottom of the Handler class inside the App\Exceptions\Handler.php file:

class Handler extends ExceptionHandler
{
    //  Default classes
    //  ...

    protected function getHttpExceptionView($e)
    {
        //  409 errors are handled specially
        //  Remove this if block entirely to serve them with the same error page as below
        if ($e->getStatusCode() === 409) {
            return "exceptions.special"; 
        }
        return "errors.custom"; // Return a "custom" file under "resources/views/errors"
    }
}

I then added the following to my error view:

<h1 >
  @if($exception)
    {{"Error " . $exception->getStatusCode().":"}}
    {{ $exception->getMessage() ? $exception->getMessage() : "page not found" }}
  @else {{ "Generic error: page not found" }}
  @endif
</h1>

This now allows me to use the abort() function in a controller, for example, to throw any HTTP error code with an optional message:

Route::get("/failtest/", function (){
        abort(404, "someone messed up");
});
  •  Tags:  
  • Related