ThomasRedstone
ThomasRedstone

Reputation: 378

Laravel handling of user generated errors

I'm quite new to Laravel, and in past applications I would generate a user warning or notice, use a custom error handler, which would send an email.

Often the errors are cases where a user enters invalid data that can't be validated, or when a third party API call returns no results.

My trouble is that Laravel halts execution and displays a whoops page for any error, so generating an error probably isn't the way I should handle this, but what is the best (correct?) way?

Upvotes: 2

Views: 409

Answers (1)

The Alpha
The Alpha

Reputation: 146191

For development environment it's recommended to use debug => true in app/config/app.php file so you'll get informative error messages. To disable it for production (recommended) just change this value to false, for example:

/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/

'debug' => false

To register a custom error handler you may declare that handler in your app/start/global.php file, for example:

// For 404 not found error
App::missing(function($e){
    return Redirect::to('/');
});

This will catch all 404 not found errors but notice another error handler available in that file by default and it's:

App::error(function(Exception $exception, $code)
{
Log::error($exception->getMessage());
});

This is the most generic error handler in Laravel means that any un-handaled error will be handled by this one and that's why declare your specific error handlers bottom of this error handler because, error handlers bubbles up from the bottom to top and this one is the parent so at last (if any custom handler was not registered or didn't catch the error) this handler will take the responsibility to handle an error if you didn't handle the error using any specific handler and didn't return any response when handling an error.

For example; to register ModelNotFoundException exception you may try this:

App::error(function(Illuminate\Database\Eloquent\ModelNotFoundException $e)
{
    return Response::make('Not Found', 404);
});

Now, since you returned a response from the handler then the parent error handler will not get fired and response will be sent to the browser. If you didn't return a response then the topmost parent handler will be fired like event bubling in JavaScript.


Read more about Errors & Logging on Laravel website.

Upvotes: 4

Related Questions