Laravel Framework, PHP & MySQL, Tutorials

Laravel add custom exception handling

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);
}

 

David Carr

David Carr

For the past 12 years, I’ve been developing applications for the web using mostly PHP. I do this for a living and love what I do as every day there is something new and exciting to learn.

In my spare time, the web development community is a big part of my life. Whether managing online programming groups and blogs or attending a conference, I find keeping involved helps me stay up to date. This is also my chance to give back to the community that helped me get started, a place I am proud to be apart of.

Besides programming I love spending time with friends and family and can often be found together going out catching the latest movie, staying in playing games on the sofa or planning a trip to someplace I’ve never been before.