Laravel - Error Handling
Laravel provides a robust error-handling system, including logging, custom exceptions, and reporting mechanisms. By default, Laravel uses Whoops for local debugging and integrates with Monolog for logging.
Step 1: Laravel Error Handling System
Laravel handles errors through the App\Exceptions\Handler
class, which is located in:
This file is responsible for:
- Reporting errors (logging)
- Rendering errors (showing responses)
Step 2: Displaying Errors in Local and Production Environments
1. Debug Mode in .env
Laravel uses the APP_DEBUG
environment variable to determine whether to show detailed error messages.
For development (show errors):
For production (hide errors):
When APP_DEBUG
is false
, a generic error page is displayed instead of detailed stack traces.
Step 3: Handling Errors with Try-Catch
You can catch exceptions in your controller to handle them gracefully.
Step 4: Custom Exception Handling
1. Creating a Custom Exception
Run the following Artisan command:
This creates a file in app/Exceptions/CustomException.php
:
2. Throwing the Custom Exception
In your controller or service, you can use:
Step 5: Handling 404 Errors (Page Not Found)
By default, Laravel returns a 404 Not Found
response when a route does not exist. However, you can customize this behavior in Handler.php
.
Modify the render()
method in app/Exceptions/Handler.php
:
Step 6: Logging Errors
Laravel logs errors using Monolog and stores them in storage/logs/laravel.log
.
1. Log an Error in storage/logs/laravel.log
You can manually log errors using the Log
facade:
2. Configure Logging in .env
Laravel supports different logging channels:
Logging options include:
single
(writes to a single log file)daily
(creates a new log file each day)syslog
(uses system logging)errorlog
(writes to PHP’serror_log
function)
You can configure logs in config/logging.php
.
Step 7: Handling Validation Errors
When validating requests, Laravel automatically throws a ValidationException
. You can catch and handle it like this:
Step 8: Using Global Exception Handling
If you want to handle specific types of exceptions globally, modify app/Exceptions/Handler.php
:
Step 9: Custom Error Pages
If APP_DEBUG=false
, Laravel will display a generic error page. You can customize these pages in:
For example, create a 404.blade.php
file:
Conclusion
✅ Laravel provides automatic error handling.
✅ You can create custom exceptions.
✅ Logging can be configured in .env
.
✅ Custom error pages improve user experience.
Would you like an example of error handling with API responses? 🚀