Friday, June 16, 2017

How to Handle Laravel 5.X Exceptions

In Laravel 5.2, all errors and exceptions, both custom and default, are handled by the Handler class in app/Exceptions/Handler.php with the help of two methods ##report & ##render.

The ##report method enables you to log raised exceptions or parse them to error logging engines. 

The ##render method return with an error message as well as response code raised by any exception. It generates a HTTP response from the exception and sends it back to the browser.

We can also override the default behavior of error handling with our own custom exception handler if we need.


/**
 * Render an exception into an HTTP response.
 *
 * @param  \Illuminate\Http\Request $request
 * @param  \Exception $e
 * @return \Illuminate\Http\Response
 */
public function render($request, Exception $e)
{
    //$request->ajax() [[AJAX REQUEST CHECK]]
    if ($e instanceof MyException) {
        if ($request->ajax()) {
            return response()->json(['error' => 'Not Found'], 404);
        }
        return response()->view('errors.custom', [], 500);
    }
    if ($this->isHttpException($e)) {
        switch ($e->getStatusCode()) {
            case 404:
                return response()->view('errors.404', [], 500);
            case 500:
                return response()->view('errors.500', [], 500);
            default:
                return $this->renderHttpException($e);
        }
    } elseif ($e instanceof TokenMismatchException) {
        return redirect()->back()->withInput()->with('error', 'Your session has expired');
    } else {
        return response()->view('errors.500', [], 500);
    }
}

And finally you have to add a 404.blade.php && 500.blade.php file in resources/view/errors to represent our custom error page.


We can also generate a 404 as well as 500 error page response by calling the abort method which takes an optional response message.

abort(404, 'The resource you are looking for could not be found');


This will check for a related resources/view/errors/404.blade.php and serve a HTTP response with the 404 status code back to the browser. The same applies for 401 and 500 or for other error status codes.








No comments:

Post a Comment