Exception/Error Handling in Laravel 11

By Hardik Savani September 4, 2024 Category : Laravel

Laravel 11 Exception Error

In this post, I will show you how to use and customize exception handling in laravel 11 framework.

Laravel exceptions are error instances thrown when unexpected events occur during application execution, aiding in error handling and debugging. They provide detailed information about errors, including stack traces and context. Developers can customize exception handling to gracefully manage errors and maintain application stability. Laravel's robust exception handling enhances development efficiency and improves overall application reliability.

In versions of Laravel before 11, exceptions were handled in the Handler.php file. However, in Laravel 11, the Handler.php file was removed, and now exceptions can be managed from the bootstrap/app.php file. Here, I will demonstrate how to handle exceptions using the renderable(), reportable(), and dontReport() methods. Let's look at some simple examples:

Laravel 11 Exception with renderable()

You can simply use the `renderable()` method to render a response for the "NotFoundHttpException" exception in the bootstrap/app.php file.

bootstrap/app.php

<?php
  
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  
return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        //
    })
    ->withExceptions(function (Exceptions $exceptions) {
            
        $exceptions->renderable(function (NotFoundHttpException $e) {
            return response()->json([
                'message' => 'Record not found.'
            ], 404);
        });
             
    })->create();

Now, you can define a simple controller method with the following code:

app/Http/Controllers/ProductController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Product;
  
class ProductController extends Controller
{

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function show($id)
    {
        $product = Product::findOrFail($id);
  
        return view('product.show', ['product' => $product]);
    }
}

Now, you can check this URL with a post ID that is not stored in the database table. So, it will return a JSON error.

http://localhost:8000/products/1212

Laravel 11 Exception with reportable()

You can simply use the `reportable()` method to report where the exception will be generated in the `bootstrap/app.php` file.

First, we will create a new exception using the following command:

php artisan make:exception InvalidProductException

you will see the new created exception like the below code:

app/Exceptions/InvalidProductException.php

<?php
  
namespace App\Exceptions;
  
use Exception;
  
class InvalidProductException extends Exception
{
    //
}

Now, we will use an exception. If it generates one, we will simply log it into the log file for now. Update the code.

bootstrap/app.php

<?php
   
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use App\Exceptions\InvalidProductException;
  
return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        //
    })
    ->withExceptions(function (Exceptions $exceptions) {
     
        $exceptions->reportable(function (InvalidProductException $e) {
            info('Product Exception: ' . $e->getMessage());
        });
  
    })->create();

Now, you can define a simple controller method with the following code:

app/Http/Controllers/ProductController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Product;
use App\Exceptions\InvalidProductException;

class ProductController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function show($id)
    {
        $product = Product::find($id);
  
        if (!$product) {
            throw new InvalidProductException("Product with ID $id not found.");
        }
  
        return view('product.show', ['product' => $product]);
    }
}

Now, you can check this URL with a post ID that is not stored in the database table. It will return a JSON error.

http://localhost:8000/products/1212

You will see the log file output like the following code:

[2024-03-10 17:58:28] local.INFO: Product Exception: Product with ID 1212 not found.

Laravel 11 Exception with dontReport()

You can simply use the `dontReport()` method to exclude exceptions from reporting in the `bootstrap/app.php` file.

bootstrap/app.php

<?php
  
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use App\Exceptions\InvalidProductException;
  
return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        //
    })
    ->withExceptions(function (Exceptions $exceptions) {
  
        $exceptions->dontReport(InvalidProductException::class);
            
    })->create();

you can get more information from here: Laravel 11 Exception.

I hope it can help you...

Shares