Laravel add custom exception handling

David Carr

Laravel Framework Tutorials PHP & MySQL

Laravel comes with support for many types of exceptions, some are handled to load a 404 page others will show an error page or 'Somewhere went wrong' page depending if debug is switched on. It's useful to be able to handle the exceptions, there may be cases where you want to show the exception message on a different page.

To handle exceptions open app/Exceptions/Handler.php and edit the render method. Checking if the exception is an instance of a set exception type you can decide what action to take.

In this example, if the HttpException occurs then a check to see if $exception->getMessage() is set, if so then a flash message is created with the message and a redirect is triggered.

If any other type of exception happens the default functionality will take care of it.

public function render($request, Exception $exception)
{

    if ($exception instanceof \Symfony\Component\HttpKernel\Exception\HttpException) {
        if ($exception->getMessage()) {
            flash($exception->getMessage(), 'danger');
            return back();
        }
    }

    return parent::render($request, $exception);
}

 

Fathom Analytics $10 discount on your first invoice using this link

Help support the blog so that I can continue creating new content!

Sponsor

Fathom Analytics $10 discount on your first invoice using this link

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2006 - 2024 DC Blog. All code MIT license. All rights reserved.