How to Handle Errors and Exceptions in Laravel 11

Handling errors and exceptions effectively is crucial for any Laravel application to ensure smooth functioning and better user experience. In Laravel 11, error and exception handling is done primarily through the App\Exceptions\Handler.php file. Let’s go through a practical example to understand how to handle errors and exceptions in Laravel 11.

Step 1: Create a Custom Exception

First, let’s create a custom exception for demonstration purposes. Run the following command in your terminal:

php artisan make:exception CustomException

This command will generate a CustomException.php file in the app\Exceptions directory.

Step 2: Implement Custom Exception Logic

Open the CustomException.php file and add custom logic to the render() method:

<?php

namespace App\Exceptions;

use Exception;

class CustomException extends Exception
{
    public function render($request)
    {
        return response()->json([
            'error' => 'Custom Error',
            'message' => $this->getMessage(),
        ], 400);
    }
}

Step 3: Implement Exception Handling Logic

Now, let’s update the App\Exceptions\Handler.php file to handle this custom exception:

<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;

class Handler extends ExceptionHandler
{
    // Other methods

    public function render($request, Throwable $exception)
    {
        if ($exception instanceof CustomException) {
            return $exception->render($request);
        }

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

Step 4: Trigger the Custom Exception

You can trigger this custom exception from anywhere in your application, for example, in a controller:

<?php

namespace App\Http\Controllers;

use App\Exceptions\CustomException;
use Illuminate\Http\Request;

class ExampleController extends Controller
{
    public function index()
    {
        // Triggering custom exception
        throw new CustomException('This is a custom exception.');
    }
}

Step 5: Test the Exception Handling

Now, when you visit the corresponding route that triggers the index() method of the ExampleController, you will get a JSON response with the custom error message and status code 400.

{
    "error": "Custom Error",
    "message": "This is a custom exception."
}

This is a basic example of how you can handle errors and exceptions in Laravel 11. You can extend this logic to handle various types of exceptions and errors in your application effectively.

Leave a Reply