Sling Academy
Home/PHP/How to handle exceptions in Laravel: A practical guide

How to handle exceptions in Laravel: A practical guide

Last updated: January 15, 2024

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.

Next Article: How to Inject Dependencies into Controllers in Laravel

Previous Article: How to create localizable (i18n) routes in Laravel

Series: Laravel & Eloquent Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array