Advanced Error/Exception Managing and Preventing in Laravel

Laravel provides centralized exception handling through the Handler.php file, allowing custom error responses and logging. You can define custom exceptions, use try-catch blocks for critical code, and log errors using Laravel’s built-in logging system. Integration with tools like Sentry or Bugsnag allows real-time error tracking. Custom error views enhance user experience by showing friendly messages instead of raw exceptions.

Centralized Error Handling: app/Exceptions/Handler.php

All exceptions are handled by the Handler class.

Customize render method:


public function render($request, Throwable $exception)
{
    if ($exception instanceof \Illuminate\Auth\AuthenticationException) {
        return redirect()->route('login');
    }

    return parent::render($request, $exception);
}

You can catch specific exceptions like:

  • ModelNotFoundException
  • ValidationException
  • HttpException
  • Custom exceptions

2. Logging Errors with Channels

Laravel uses Monolog under the hood. You can configure logging in config/logging.php.

Example: Log to single file


LOG_CHANNEL=single

Log types supported:

  • single, daily, slack, papertrail, syslog, errorlog

Log manually:

app/Exceptions/Handler.php


use Illuminate\Support\Facades\Log;

Log::error('Something went wrong!');
Log::warning('Check this logic.');
Log::info('Action successful.');

3. Custom Exception Classes

Use your own exceptions for more control.

Put this comment in your project terminal:


php artisan make:exception CustomException

throw new \App\Exceptions\CustomException('Something failed.');

In Handler.php, catch it and respond accordingly.

4. Use Try-Catch Blocks for Error Prevention

File: app/Http/Controllers/UserController.php


try {
    // risky code
    $user = User::findOrFail($id);
} catch (\Exception $e) {
    Log::error('User not found: ' . $e->getMessage());
    return redirect()->back()->withErrors('User not found.');
}

5. Validation Exception Handling

Automatically caught and handled if you use:

app/Http/Controllers/UserController.php


$request->validate([
    'email' => 'required|email',
]);

6. Use report() in Handler.php to Integrate Error Trackers

Example: Sentry, Bugsnag, etc.

app/Exceptions/Handler.php


public function report(Throwable $exception)
{
    if (app()->bound('sentry') && $this->shouldReport($exception)) {
        app('sentry')->captureException($exception);
    }

    parent::report($exception);
}

7. Display Custom Error Pages

In resources/views/errors/ add:

  • 404.blade.php → Not Found
  • 500.blade.php → Server Error
  • 403.blade.php → Forbidden

 

Summary Table

Feature Tool/Location
Global Exception Handling app/Exceptions/Handler.php
Custom Exception Classes php artisan make:exception
Logging Log::error(), config/logging.php
External Reporting Sentry, Bugsnag, etc.
Custom Error Pages resources/views/errors/
Try-Catch for local logic try { } catch { }