Sept. 29, 2017, midnight

Error Handling in Laravel

By : Eric A. Scuccimarra

For a Laravel application I am working on the need arose to log errors to the database rather than to log files. I also wanted to show a custom error page instead of Laravel's default error page. This is my solution:

In app/Exceptions/Handler.php:

public function report(Exception $exception)
{
    if(!config('app.debug')) {
        if ($this->shouldReport($exception)) {
            $this->logError($exception);
        }
    }
    if(env('APP_ENV') == 'local'){
        parent::report($exception);
    }
}

public function render($request, Exception $exception)
{
    if(!config('app.debug')) {
        if($this->shouldReport($exception)){
            return response()->view('errors.500', compact('exception'));
        }
    }
    return parent::render($request, $exception);
}

Function report checks to see if APP_ENV is set to local, if so it displays the error as normal. If it is not local it calls function logError which writes the error to the database. 

Function render also checks APP_DEBUG and if it is set to true it reports the error to the screen as normal. If it is set to false it returns a custom error template which is stored in resources/views/error/500.blade.php.

 

Labels: coding , laravel , php2

There are no comments for this article.

Login or register to comment