CRITICAL: Avoid try-catch blocks in controllers
This project uses Laravel's centralized exception handling system configured in bootstrap/app.php.
// ❌ 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);
}
}// ✅ 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]);
}- Embrace throwing exceptions for error conditions
- Use
abort()helper for common HTTP errors - Let Laravel handle exceptions through centralized system
- Configure exception responses in
bootstrap/app.php - Validation exceptions are handled automatically by Form Requests
- Use
throw_if()andthrow_unless()for conditional exceptions
ValidationException- Form validation errors (automatic from Form Requests)ModelNotFoundException- Resource not found (automatic fromfindOrFail())AuthorizationException- Permission denied (automatic from policies)HttpForbiddenException- Useabort(403)HttpNotFoundException- Useabort(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