Exception/Error Handling in Laravel 11
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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Register Schedule Command in Laravel 11?
- Laravel 11 New a Health Check Route Example
- How to Create Custom Middleware in Laravel 11?
- How to Publish Broadcasting Channels Route File in Laravel 11?
- How to Create and Use Traits in Laravel 11?
- How to use new Dumpable Trait in Laravel 11?
- How to Publish API Route File in Laravel 11?
- How to Create and Use Enum in Laravel 11?
- How to Publish Config Files in Laravel 11?
- How to Create Interface in Laravel 11?
- How to Create Custom Class in Laravel 11?
- How to Publish the lang Folder in Laravel 11?
- What’s New in Laravel 11: New Features and Latest Updates
- How to Install Laravel 11 Application?