Custom Exceptions in Laravel
Creating a custom exception in Laravel is particularly useful to be able to customize exceptions when performing certain operations according to the business logic of your application; if you create an order and it has an invalid format, a record not found, etc; for example, if a resource is not found:
app/Exceptions/ResourceNotFoundException.php
namespace App\Exceptions;
use Exception;
class ResourceNotFoundException extends Exception
{
// custom properties or methods...
}
And to use it, we use the throw to throw the exception:
use App\Models\User;
use App\Exceptions\ResourceNotFoundException;
public function getUserById($id)
{
$user = User::find($id);
if (!$user) {
throw new ResourceNotFoundException("User with ID $id not found.");
}
return $user;
}
Video Transcript
The next thing I wanted to show you is how you can handle custom exceptions in Laravel, that is, here we define a section that the end is a class like almost everything else and here we use it here we put the true to launch the section there we put the message and that would be practically all this would be quite useful if you add it to what we saw a little later which is for example controlling the exceptions by asking for the type then here you could have greater control of this and I think we have already closed the cycle a little with what we saw before, that is, we have greater control of what is happening in the application without the need to be passing codes or evaluating texts but directly something more robust like an exception, a custom exception; of course, and therefore we can create as much as our application requires so, having clarified a little the context of all this well here obviously it is a class you can define what you want here in case it is necessary.
We create a class like the one shown before, usually the name is more than enough but to create a class you can define anything again, there we go again; I'm going to create a folder since we don't have one called exceptions and we create the custom exception as we showed in the previous code.
Using custom exception
We define the class and extend the exception and I'm not going to do anything else here since it's usually not necessary, with this we have the template, so I'm going to use it, for example, as shown in the previous code.
For this purpose, which is to launch the section, in this case we are not capturing it but launching it, this is something in PHP, again, the trycatch is to prevent the application, as they say colloquially, from exploding here. It shows you the error on the screen, there it is capturing it and it is being handled, for example, to save it in the log:
bootstrap/app.php
use App\Exceptions\InvalidOrderException;
use Illuminate\Http\Request;
->withExceptions(function (Exceptions $exceptions) {
$exceptions->render(function (ResourceNotFoundException $e, Request $request) {
// dd(auth()->user());
if ($request->is('api/*')) {
return response()->json(['message' => '404']);
} else {
return response()->view('errors.NotFoundHttpException');
}
});
})->create();
})
As who would say an example of this Of course, you would already use this in production in the sense that you place it in a log, in a specific log, you send an email, it all depends. But this is quite useful for the reasons mentioned above. Suppose it is a payment order and you sell expensive products, then you will surely want to send an email, push notifications, etc. You can do a lot of things and you can control it very effectively.
- Andrés Cruz
This material is part of my complete course and book; You can purchase them from the books and/or courses section, Curso y Libro Laravel 11 con Tailwind Vue 3, introducción a Jetstream Livewire e Inerta desde cero - 2024.
Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter