Search code examples
phplaravelerror-handlinglaravel-8http-status-codes

Make all error status codes return a single custom view


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.


Solution

  • 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.