How to Handle API Errors in Laravel: Simple Guide
try-catch blocks or custom exception handlers in app/Exceptions/Handler.php. Return JSON responses with appropriate HTTP status codes and error messages to inform API clients clearly.Why This Happens
API errors happen when your Laravel app encounters unexpected issues like missing data, invalid input, or server problems but does not properly catch and respond to them. Without handling, Laravel returns default HTML error pages, which are not suitable for API clients expecting JSON.
<?php Route::get('/user/{id}', function ($id) { $user = App\Models\User::findOrFail($id); // Throws ModelNotFoundException if user not found return response()->json($user); });
The Fix
Use Laravel's exception handler to catch errors and return JSON responses with clear messages and HTTP status codes. Customize render() method in app/Exceptions/Handler.php to handle exceptions like ModelNotFoundException and ValidationException. This ensures API clients get consistent JSON error responses.
<?php namespace App\Exceptions; use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler; use Throwable; use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Validation\ValidationException; class Handler extends ExceptionHandler { public function render($request, Throwable $exception) { if ($request->expectsJson()) { if ($exception instanceof ModelNotFoundException) { return response()->json(['error' => 'Resource not found'], 404); } if ($exception instanceof ValidationException) { return response()->json(['errors' => $exception->errors()], 422); } return response()->json(['error' => $exception->getMessage()], 500); } return parent::render($request, $exception); } }
Prevention
Always validate input data using Laravel's FormRequest or Validator before processing. Use centralized exception handling for consistent API error responses. Test your API endpoints with tools like Postman to ensure errors return JSON with proper status codes. Follow RESTful API standards for error codes.
Related Errors
Common related errors include:
- ValidationException: Happens when input data fails validation rules.
- AuthenticationException: Occurs when API requests lack valid authentication tokens.
- AuthorizationException: When a user tries to access a resource they are not allowed to.
Handle these in Handler.php similarly by returning JSON with appropriate status codes like 401 or 403.