0
0
LaravelDebug / FixBeginner · 4 min read

How to Handle API Errors in Laravel: Simple Guide

In Laravel, handle API errors by using 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
<?php

Route::get('/user/{id}', function ($id) {
    $user = App\Models\User::findOrFail($id); // Throws ModelNotFoundException if user not found
    return response()->json($user);
});
Output
{ "message": "No query results for model [App\\Models\\User] $id" } // Or default HTML error page if not caught
🔧

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
<?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);
    }
}
Output
{ "error": "Resource not found" } // or { "errors": { "email": ["The email field is required."] } }
🛡️

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.

Key Takeaways

Use Laravel's exception handler to return JSON error responses for API requests.
Catch specific exceptions like ModelNotFoundException and ValidationException for clear messages.
Validate input data before processing to avoid errors.
Test API error responses to ensure clients receive consistent JSON with correct HTTP codes.
Follow RESTful standards for error handling and status codes.