Exception handling in laravel 8 with example

Exception handling is a critical aspect of any web application, and Laravel 8 provides robust and elegant ways to handle exceptions. Exception handling is the process of detecting, reporting, and resolving errors that may occur during the execution of a program. In this article, we will discuss Laravel 8’s exceptional handling capabilities and explore different examples to help you understand how to use them effectively.

Laravel 8 Throw Exception with Message

Laravel 8 allows developers to throw exceptions with a custom message that provides more context about the error. This feature can help users and developers to better understand the error’s nature and the steps needed to resolve it.

To throw an exception with a custom message, we can use the throw keyword followed by the new keyword and the Exception class. We can then pass the custom message as a parameter to the Exception class constructor. Here’s an example:

throw new Exception('The email address is already taken.');

In this example, we’re throwing an Exception with the custom message ‘The email address is already taken.’ We can use this technique anywhere in our code to indicate an error condition and provide a more detailed explanation of the error.

Read Also : How to generate and download pdf using Laravel Snappy

Laravel 8 Abort with Message

Sometimes, we may want to stop the execution of a script immediately and return a message to the user. In such cases, we can use Laravel 8’s abort function. The abort function returns an HTTP response with the specified status code and message.

Here’s an example of how to use the abort function:

abort(404, 'The requested resource could not be found.');

In this example, we’re returning an HTTP response with the status code 404 and the message ‘The requested resource could not be found.’ We can use any HTTP status code and message as per our requirement.

How to Display Error Message in Laravel 8

Laravel 8 provides several ways to display error messages. The most common way is to use Laravel’s built-in errors variable. The errors variable is automatically available in all Blade templates and contains any errors that occurred during form submission.

Here’s an example of how to display error messages in a Blade template:

@if($errors->any())    <div class="alert alert-danger">        <ul>            @foreach ($errors->all() as $error)                <li>{{ $error }}</li>            @endforeach        </ul>    </div>@endif

In this example, we’re checking if there are any errors in the errors variable. If there are any errors, we’re displaying them in an unordered list.

Read Also : How to generate pdf using tcpdf in laravel with example

Laravel Get Error Message in Blade

In addition to displaying error messages, Laravel 8 also allows us to retrieve individual error messages. We can use the getMessage method on the MessageBag object to retrieve the first error message for a specific field.

Here’s an example of how to retrieve the first error message for a field named email:

@if($errors->has('email'))    <p>{{ $errors->first('email') }}</p>@endif

In this example, we’re checking if there are any errors for the email field. If there are any errors, we’re displaying the first error message for that field.

Laravel Eloquent Exception Handling

Laravel 8’s Eloquent ORM provides built-in exception handling that makes it easy to handle errors that may occur during database operations. When an Eloquent query encounters an error, it throws a QueryException.

To handle Eloquent exceptions, we can catch the QueryException and handle the error condition as needed. For example, if we’re trying to insert a new record into the database and there’s a unique key violation, we can catch the QueryException and display an appropriate error message to the user.

Here’s an example of how to catch a QueryException and display an error message:

try {    // Attempt to insert a new record into the database    MyModel::create($data);} catch (QueryException $e) {    // Handle the error condition    if ($e->errorInfo[1] == 1062) {        return redirect()->back()->withErrors(['email' => 'The email address is already taken.']);    }}

In this example, we’re catching a QueryException and checking if the error code is 1062, which indicates a unique key violation. If there’s a unique key violation, we’re redirecting the user back to the previous page and displaying an error message.

Laravel Custom Exception Message

In addition to the built-in exceptions provided by Laravel, we can also define our custom exceptions to handle specific error conditions. Custom exceptions can be defined by extending the Exception class or any other built-in exception class.

Here’s an example of how to define a custom exception that’s thrown when a user tries to access a restricted resource:

class AccessDeniedException extends Exception{    protected $message = 'Access denied.';}

In this example, we’re creating a new exception class called AccessDeniedException that extends the Exception class. We’re also defining a custom message for this exception using the $message property.

We can then use this custom exception in our code to handle the error condition. For example, if we’re trying to access a restricted resource and the user doesn’t have permission, we can throw the AccessDeniedException like this:

if (!$user->canAccessResource()) {    throw new AccessDeniedException();}

Laravel Catch All Exceptions

In some cases, we may want to catch all exceptions that are thrown in our application and handle them in a centralized location. Laravel 8 provides a global exception handler that allows us to catch all exceptions and handle them in a single place.

To define a global exception handler, we can create a new PHP class and implement the ExceptionHandler interface. We can then define the report and render methods to handle the exception.

Here’s an example of how to define a global exception handler that logs and displays a user-friendly error page when an exception is thrown:

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;class MyExceptionHandler extends ExceptionHandler{    public function report(Exception $exception)    {        parent::report($exception);    }    public function render($request, Exception $exception)    {        if ($exception instanceof AccessDeniedException) {            return response()->view('errors.access_denied', [], 403);        }        if ($exception instanceof RecordNotFoundException) {            return response()->view('errors.record_not_found', [], 404);        }        return parent::render($request, $exception);    }}

In this example, we’re creating a new exception handler class called MyExceptionHandler that extends the built-in ExceptionHandler class. We’re then defining the report and render methods to handle exceptions.

In the render method, we’re checking if the exception is an instance of one of our custom exceptions (AccessDeniedException and RecordNotFoundException) and returning a custom error page with an appropriate HTTP status code. If the exception is not one of our custom exceptions, we’re calling the parent render method to handle the exception.

To use our custom exception handler, we need to register it in the app/Exceptions/Handler.php file:

public function register(){    $this->renderable(function (Exception $e, $request) {        return app(MyExceptionHandler::class)->render($request, $e);    });}

In this example, we’re registering our custom exception handler by defining a closure that returns an instance of MyExceptionHandler to handle exceptions.

Conclusion

Exception handling is an essential part of any application development, and Laravel 8 provides powerful tools for handling exceptions in a flexible and user-friendly way. With the built-in exception classes, we can handle common error conditions easily, and with custom exceptions, we can handle specific error conditions unique to our application. Additionally, the global exception handler allows us to catch all exceptions in a centralized location and handle them in a consistent way. By taking advantage of these features, we can create robust and reliable applications that provide a great user experience even in the face of unexpected errors.

Comments