🎉🎉 Larasense is officially launched 🎉🎉
- Your Hub for Laravel News, Trends & Updates

Understanding Exception Handling in Laravel

laravel
tutorial
exception
Nabil Hassen
Nabil Hassen
Dec 25, 2024
Exception Handling in Laravel
Last updated on Dec 24, 2024
Table of contents:

Exception handling is an essential part of any application, allowing developers to gracefully manage errors and ensure users have a smooth experience. Laravel simplifies this process by offering a robust error and exception handling system out of the box. In this guide, we’ll explore step-by-step how to leverage Laravel's exception handling capabilities in a beginner-friendly manner.

Understanding the Basics of Exception Handling in Laravel

Laravel comes pre-configured with a robust error and exception-handling mechanism. This ensures you don’t have to start from scratch.

The core of this functionality is the $exceptions object, found in the bootstrap/app.php file, which controls how exceptions are reported (logged or sent to an external service) and rendered (displayed to users).

Setting Up Debugging

Laravel uses the APP_DEBUG variable in the .env file to determine how much error information to display:

  • Local Development: Set APP_DEBUG=true to show detailed error messages.
  • Production: Always set APP_DEBUG=false to avoid exposing sensitive information.

Update the .env file:

APP_DEBUG=true

Reporting Exceptions

Laravel logs exceptions automatically based on the logging configuration. To customize this behavior, you can define exception-specific reporting logic.

Example: Reporting a Custom Exception

In bootstrap/app.php:

->withExceptions(function (Exceptions $exceptions) {
$exceptions->report(function (InvalidOrderException $e) {
// Custom reporting logic
})->stop();
});
  • Use ->stop() to prevent default logging.
  • Return false in the closure to skip logging entirely.

Adding Global Context to Logs

To make your logs more meaningful, you can include contextual data:

Global Context

Define global data that should appear in every log entry:

In bootstrap/app.php:

->withExceptions(function (Exceptions $exceptions) {
$exceptions->context(fn () => ['user_id' => auth()->id()]);
});

Exception-Specific Context

Add context to specific exceptions by defining a context method in your exception class:

public function context(): array
{
return ['order_id' => $this->orderId];
}

Rendering Exceptions

By default, Laravel converts exceptions into HTTP responses. You can override this behavior for specific exceptions.

Example: Custom Rendering for Invalid Orders

In bootstrap/app.php:

use App\Exceptions\InvalidOrderException;
use Illuminate\Http\Request;
 
->withExceptions(function (Exceptions $exceptions) {
$exceptions->render(function (InvalidOrderException $e, Request $request) {
return response()->view('errors.invalid-order', [], 500);
});
});
  • The render method can also handle built-in exceptions like NotFoundHttpException.

Example: For API responses

Render exceptions as JSON:

$exceptions->render(function (NotFoundHttpException $e, Request $request) {
return $request->is('api/*')
? response()->json(['message' => 'Not found'], 404)
: null;
});

Creating Custom HTTP Error Pages

Laravel lets you create custom error pages for various HTTP status codes. To customize a 404 error page:

Steps to Customize:

  1. To customize default error templates, publish them using:
    php artisan vendor:publish --tag=laravel-errors
  2. Add your custom content to the 404.blade.php view:
    <h2>{{ $exception->getMessage() }}</h2>
    <p>Sorry, the page you’re looking for doesn’t exist.</p>
  3. Test the page by navigating to a non-existent route.

You can also define fallback templates for groups of errors, like 4xx.blade.php for all 4xx errors.

Using Reportable and Renderable Exceptions

Instead of defining reporting and rendering logic globally, you can implement it directly in custom exception classes.

Example: Custom Exception Class

Create a new exception:

php artisan make:exception InvalidOrderException

In App\Exceptions\InvalidOrderException:

namespace App\Exceptions;
 
use Exception;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
 
class InvalidOrderException extends Exception
{
public function report(): void
{
// Custom reporting logic
}
 
public function render(Request $request): Response
{
return response()->view('errors.invalid-order', [], 500);
}
}

Throttling Exceptions

To avoid flooding logs with duplicate errors, Laravel allows you to throttle reported exceptions.

Example: Throttling Exceptions

In bootstrap/app.php:

use Illuminate\Support\Lottery;
 
->withExceptions(function (Exceptions $exceptions) {
$exceptions->throttle(fn () => Lottery::odds(1, 1000));
});
  • This ensures only one out of every 1000 identical exceptions is logged.

Ignoring Exceptions

You can exclude certain exceptions from being reported by adding them to the dontReport list or implementing the ShouldntReport interface.

Example: Adding Exceptions to dontReport List

$exceptions->dontReport([
InvalidOrderException::class,
]);

Example: Marking Exceptions as Non-Reportable

namespace App\Exceptions;
 
use Exception;
use Illuminate\Contracts\Debug\ShouldntReport;
 
class CustomException extends Exception implements ShouldntReport
{
// ...
}

Handling HTTP Exceptions

To trigger specific HTTP errors programmatically, use the abort helper:

Example: Trigger a 404 Error

abort(404, 'Page not found');

Conclusion

Laravel’s exception handling system is designed to be flexible, allowing developers to customize and control error reporting and rendering as needed. By mastering these techniques, you can ensure your application handles errors gracefully while maintaining a seamless user experience.

Nabil Hassen
Nabil Hassen
Full Stack Web Developer

Stay Updated.

I'll you email you as soon as new, fresh content is published.

Thanks for subscribing to my blog.

Latest Posts

Larasenes Logo
Larasense
Stay updated on Laravel news, trends, and updates with curated content from top blogs, YouTube, and podcasts in a sleek, user-friendly design.