Laravel - Error Handling

Laravel - Error Handling

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:

app/Exceptions/Handler.php

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):

    APP_DEBUG=true
  • For production (hide errors):

    APP_DEBUG=false

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.

use Exception; use Illuminate\Http\Request; public function store(Request $request) { try { // Your logic here } catch (Exception $e) { return response()->json(['error' => 'Something went wrong!'], 500); } }

Step 4: Custom Exception Handling

1. Creating a Custom Exception

Run the following Artisan command:

php artisan make:exception CustomException

This creates a file in app/Exceptions/CustomException.php:

namespace App\Exceptions; use Exception; class CustomException extends Exception { public function report() { // Custom logging (optional) } public function render($request) { return response()->json([ 'error' => 'A custom error occurred!' ], 400); } }

2. Throwing the Custom Exception

In your controller or service, you can use:

throw new \App\Exceptions\CustomException();

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:

public function render($request, Throwable $exception) { if ($exception instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) { return response()->json(['error' => 'Resource not found'], 404); } return parent::render($request, $exception); }

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:

use Illuminate\Support\Facades\Log; Log::error('An unexpected error occurred.'); Log::info('This is an informational message.'); Log::warning('This is a warning.');

2. Configure Logging in .env

Laravel supports different logging channels:

LOG_CHANNEL=stack

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’s error_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:

use Illuminate\Http\Request; use Illuminate\Validation\ValidationException; public function store(Request $request) { try { $request->validate([ 'name' => 'required|min:3', ]); } catch (ValidationException $e) { return response()->json(['error' => $e->errors()], 422); } }

Step 8: Using Global Exception Handling

If you want to handle specific types of exceptions globally, modify app/Exceptions/Handler.php:

public function register() { $this->renderable(function (\App\Exceptions\CustomException $e, $request) { return response()->json(['message' => 'Custom error occurred'], 400); }); }

Step 9: Custom Error Pages

If APP_DEBUG=false, Laravel will display a generic error page. You can customize these pages in:

resources/views/errors/

For example, create a 404.blade.php file:

@extends('layouts.app') @section('content') <h1>Page Not Found</h1> <p>Sorry, the page you are looking for does not exist.</p> @endsection

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? 🚀

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close