Laravel provides centralized exception handling through the Handler.php
file, allowing custom error responses and logging. You can define custom exceptions, use try-catch blocks for critical code, and log errors using Laravel’s built-in logging system. Integration with tools like Sentry or Bugsnag allows real-time error tracking. Custom error views enhance user experience by showing friendly messages instead of raw exceptions.
Centralized Error Handling: app/Exceptions/Handler.php
All exceptions are handled by the Handler
class.
Customize render method:
public function render($request, Throwable $exception)
{
if ($exception instanceof \Illuminate\Auth\AuthenticationException) {
return redirect()->route('login');
}
return parent::render($request, $exception);
}
You can catch specific exceptions like:
ModelNotFoundException
ValidationException
HttpException
- Custom exceptions
2. Logging Errors with Channels
Laravel uses Monolog under the hood. You can configure logging in config/logging.php
.
Example: Log to single file
LOG_CHANNEL=single
Log types supported:
single
,daily
,slack
,papertrail
,syslog
,errorlog
Log manually:
app/Exceptions/Handler.php
use Illuminate\Support\Facades\Log;
Log::error('Something went wrong!');
Log::warning('Check this logic.');
Log::info('Action successful.');
3. Custom Exception Classes
Use your own exceptions for more control.
Put this comment in your project terminal:
php artisan make:exception CustomException
throw new \App\Exceptions\CustomException('Something failed.');
In Handler.php
, catch it and respond accordingly.
4. Use Try-Catch Blocks for Error Prevention
File: app/Http/Controllers/UserController.php
try {
// risky code
$user = User::findOrFail($id);
} catch (\Exception $e) {
Log::error('User not found: ' . $e->getMessage());
return redirect()->back()->withErrors('User not found.');
}