How can I make Laravel return a custom error for a JSON REST API

How can I make Laravel return a custom error for a JSON REST API

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

How can I make Laravel return a custom error for a JSON REST API

When building a RESTful API, the standard App::abort() helper is often too blunt an instrument. It halts execution and triggers the application's default exception handler. For web interfaces, this might render a nice 500 page or a stack trace if debugging is on. However, for a JSON API, you likely need precise control over the response body to return a structured array like ["code" => 401, "message" => "Invalid User"].

The core issue is that App::abort() defaults to returning an HTML view unless explicitly told otherwise, and even then, it doesn't guarantee the specific JSON structure you require. To solve this, you need to intercept the exception before it hits the default handler or configure your global error handling specifically for JSON requests.

The Modern Approach: Using throw with Response

In modern Laravel versions (8.0+), the recommended pattern is to avoid App::abort() in favor of throwing standard exceptions and catching them, or using the Response facade to build the payload directly. This gives you full ownership of the HTTP response object.

If you are inside a controller method, you can return a structured JSON response directly:

return response()->json([
    'code' => 401,
    'message' => 'Invalid User',
], 401);

This is the cleanest approach when the logic for generating the error is local to that controller method. It bypasses the exception throwing mechanism entirely, ensuring the response format matches your API contract exactly.

Handling Errors Globally with Exception Handlers

If you prefer to keep your controllers clean by simply throwing an exception (e.g., auth()->guard('api')->reject()), you must configure Laravel's global exception handler to output JSON instead of HTML.

Laravel provides a built-in mechanism for this via the App\Exceptions\Handler class. You can modify the report and render methods to detect when an exception occurs during an AJAX or API request.

A common pattern involves checking if the request is an HTTP JSON request:

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;

public function render($request, Throwable $exception)
{
    // If it's a JSON request, return custom JSON structure
    if ($request->expectsJson()) {
        return response()->json([
            'code' => $exception->getStatusCode() ?: 500,
            'message' => config('app.debug') 
                ? $exception->getMessage() 
                : 'An error occurred',
        ], $exception->getStatusCode());
    }

    // Fall back to default rendering for non-JSON requests
    return parent::render($request, $exception);
}

By checking $request->expectsJson(), you ensure that only API clients receive the custom structured array, while web browsers or direct curl calls without a Content-Type: application/json header still see the standard HTML error pages. This distinction is vital for maintaining a consistent user experience across different access methods.

Trade-offs and Considerations

Using App::abort() directly in older Laravel versions or legacy codebases often relies on the default exception renderer. If you rely on that, you lose the ability to customize the JSON structure without overriding the global handler. The trade-off is that global handlers add a layer of abstraction; if your error messages contain sensitive data (like stack traces in production), you must be careful with what you expose in the message key.

In the example above, the code checks config('app.debug'). This is a critical safety measure. In production environments, you should never return raw exception messages to clients; instead, return a generic string like "An error occurred" or a specific API-specific message. Exposing internal details can aid attackers in probing your system.

Additionally, ensure that your global exception handler logic does not interfere with Laravel's built-in validation exceptions if you are using Form Requests. Validation errors often come with their own structure. You might want to add a condition to only apply this custom JSON formatting for specific exception types or status codes, avoiding the override of standard validation responses which clients might already know how to parse.

Conclusion

To achieve a custom error format like ["code" => 401, "message" => "Invalid User"], stop relying on the default behavior of App::abort(). Instead, either return a JsonResponse directly in your controller or configure your global exception handler to detect JSON requests and inject the custom structure. This approach ensures your API remains consistent, secure, and adheres to modern RESTful best practices.

Our network