How to handle exceptions in Laravel: A practical guide

Updated: January 15, 2024 By: Guest Contributor Post a comment

Introduction

Laravel, a robust MVC framework for PHP, has a powerful error and exception handling system. Handling exceptions effectively is crucial for building a reliable application and providing a pleasant user experience. This guide will teach you how to manage exceptions systematically, and show how Laravel makes it easier to handle errors that arise during the execution of your application.

Understanding Exceptions in Laravel

Laravel’s exception handling is concentrated in the app\Exceptions\Handler.php file. It uses a class named Handler that contains two methods: report() and render(). Here’s a quick overview:

  • report(): This method logs exceptions. You can report exceptions to an external service like Bugsnag or Sentry here.
  • render(): It responds to exceptions and determines what your application should display to the user.

Basic Exception Handling

Here’s a simple example of how to create custom exceptions:

class MyCustomException extends \Exception {}

// Throwing the custom exception
throw new MyCustomException('Something went wrong');

To handle this exception, override the render() method:

public function render($request, Exception $exception)
{
    if ($exception instanceof MyCustomException) {
        return response()->view('errors.custom', [], 500);
    }

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

Validation Exceptions

Laravel provides a helpful feature to deal with validation errors automatically. Use the validate helper in your controller methods to harness this:

public function store(Request $request)
{
    $validatedData = $request->validate([
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ]);

    // The blog post is valid, keep going...
}

If validation fails, a ValidationException is thrown and caught by Laravel’s exception handler. The user is redirected back to the previous location with the validation errors automatically flashed to the session.

Authentication Exceptions

In authentication, if a user tries to access a route that requires authentication, a Illuminate\Auth\AuthenticationException is thrown. Laravel redirects to a login page or, for API requests, returns a JSON response with a 401 status code. It’s set up out-of-the-box, but you can customize it in the Handler class.

protected function unauthenticated($request, AuthenticationException $exception)
{
    return $request->expectsJson()
        ? response()->json(['message' => 'Unauthenticated.'], 401)
        : redirect()->guest(route('login'));
}

Reporting and Logging Exceptions

Reporting is about logging the exception or sending it to an external service like Sentry. By default, Laravel logs exceptions but you can customize this:

public function report(Exception $exception)
{
    if ($exception instanceof CustomException) {
        // Send the exception to an external service
    }

    parent::report($exception);
}

To ignore certain exceptions from being reported:

protected $dontReport = [
    \InvalidArgumentException::class,
    \Illuminate\Auth\AuthenticationException::class
];

Custom HTTP Error Pages

Laravel allows you to easily create custom error pages for different HTTP status codes. For example, for a 404 error page, create a 404.blade.php file in your resources/views/errors/ directory. When a 404 exception is thrown, Laravel will automatically use this view.

Conclusion

This tutorial gave you a tour of Laravel’s built-in exception handling capabilities. You’ve learned how to work with exceptions effectively in order to create applications that gracefully handle unexpected scenarios. Remember, good exception handling is essential for maintaining quality user experiences and ensuring the reliability of your applications.