Error Handling & Exception Management

Centralized Error Handling

Laravel uses app/Exceptions/Handler.php for global error management. Customize the render and report methods to handle exceptions consistently across your application.

  • Use the report method to log exceptions or send them to external services (e.g., Sentry, Bugsnag).
  • Use the render method to return user-friendly error responses for web and API endpoints.

Example: Customizing Handler

public function render($request, Throwable $exception)
{
    if ($request->expectsJson()) {
        return response()->json([
            'error' => $exception->getMessage()
        ], 500);
    }
    return parent::render($request, $exception);
}

Custom Exceptions

Create custom exception classes for domain-specific errors. Extend the base Exception class and provide meaningful messages.

class PaymentFailedException extends Exception
{
    public function __construct($message = 'Payment failed.')
    {
        parent::__construct($message);
    }
}
  • Throw custom exceptions in your business logic and catch them in the handler.

Logging & Reporting

Use Laravel's logging facilities (Log facade) for error reporting. Log errors with appropriate severity levels and avoid exposing sensitive information.

use Illuminate\Support\Facades\Log;
Log::error('Payment failed for user: ' . $user->id);
  • Integrate with external error tracking services for production.
  • Use different log channels for different environments.

User-Friendly Error Messages

Display clear, actionable error messages to users. Avoid technical jargon and stack traces in user-facing errors.

  • Use custom error pages for common HTTP errors (404, 500) in resources/views/errors/.
  • For APIs, return structured error responses with a message and code.

Example: Custom Error Page

{{-- resources/views/errors/404.blade.php --}}
@extends('layouts.app')
@section('content')
    <h1>Page Not Found</h1>
    <p>The page you are looking for does not exist.</p>
@endsection

Best Practices

  • Always catch and handle exceptions at the appropriate level.
  • Log all unexpected errors for later analysis.
  • Use custom exceptions for business logic errors.
  • Provide helpful error messages to users and developers.
  • Test error handling in both development and production environments.