Error handlers order in Laravel

Standard

Error handlers are a neat feature of Laravel. They allow you to deal with custom exceptions so that you know what to do when something wrong happens. If you want to play with error handlers, you need to know two vital things:

  1. If an exception handler returns a response, that response will be sent to the browser and no other error handlers will be called ;
  2. Handlers are called based on the type-hint of the Exception they handle. If two handlers handle the same exception, the last one will be called first.

About error handlers order

An example:

App::error(function(MyCustomException $exception, $code)
{
	// This handler will not be called first
});

App::error(function(MyCustomException $exception, $code)
{
	// This handler will be called first
});

Error handlers and responses

If your last handler returns a response, your previous handler will not be called because of the first rule.

App::error(function(MyCustomException $exception, $code)
{
	// This handler will not be called AT ALL
});

App::error(function(MyCustomException $exception, $code)
{
	// This handler will be called first
	$data = ['title' => 'Error occured'];

	// We are returning a response: no other error handlers will be called
	return Response::view('errors.default', $data, $code);
});

Playing with error handlers order

Let’s say you want an error handler to be called at the bottom of the stack. This is very useful for example if you are using a package that registers an error handler and you want one of your error handlers to be called after. Laravel provides the App::pushError() function that registers an error handler at the bottom of the stack.

App::error(function(MyCustomException $exception, $code)
{
	// This handler will be called first
	// If we are returning a response here, no other error handlers will be called
});

App::pushError(function(MyCustomException $exception, $code)
{
	// This handler will be called at the end
	$data = ['title' => 'Error occured'];

	return Response::view('errors.default', $data, $code);
});

Sounds great? Give me a follow on Twitter or learn more about me.