Skip to content

Instantly share code, notes, and snippets.

@muhajirinlpu
Created October 22, 2025 19:30
Show Gist options
  • Select an option

  • Save muhajirinlpu/ce9c10dd492040f97dd93e142b760019 to your computer and use it in GitHub Desktop.

Select an option

Save muhajirinlpu/ce9c10dd492040f97dd93e142b760019 to your computer and use it in GitHub Desktop.

Exception Handling Pattern

CRITICAL: Avoid try-catch blocks in controllers

This project uses Laravel's centralized exception handling system configured in bootstrap/app.php.

Do NOT use this pattern:

// ❌ WRONG - Don't use try-catch in controllers
public function store(Request $request)
{
    try {
        // business logic
        return response()->json(['success' => true]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'Operation failed',
            'error' => $e->getMessage()
        ], 500);
    }
}

DO use this pattern:

// ✅ CORRECT - Let exceptions bubble up to centralized handler
public function store(Request $request)
{
    // business logic - if it throws, Laravel handles it
    // Validation exceptions automatically return 422
    // Model not found automatically return 404
    // Other exceptions handled by bootstrap/app.php configuration

    return response()->json(['success' => true]);
}

Principles:

  1. Embrace throwing exceptions for error conditions
  2. Use abort() helper for common HTTP errors
  3. Let Laravel handle exceptions through centralized system
  4. Configure exception responses in bootstrap/app.php
  5. Validation exceptions are handled automatically by Form Requests
  6. Use throw_if() and throw_unless() for conditional exceptions

Exception Types to Use:

  • ValidationException - Form validation errors (automatic from Form Requests)
  • ModelNotFoundException - Resource not found (automatic from findOrFail())
  • AuthorizationException - Permission denied (automatic from policies)
  • HttpForbiddenException - Use abort(403)
  • HttpNotFoundException - Use abort(404)
  • Custom business exceptions with meaningful messages

This approach ensures:

  • Consistent error response formats
  • Proper HTTP status codes
  • Automatic logging and monitoring
  • Cleaner, more focused controller methods
  • Centralized exception management and debugging
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment