← All posts

Josh Davies

Every Error Should Look the Same

If your API returns five different error shapes, every client ends up guessing. Pick one shape, render every failure into it, and give the frontend a code it can switch on instead of a sentence it has to parse.

  • api
  • laravel
  • php
  • typescript
  • architecture

Ask an API for something that doesn't exist and see what comes back.

Maybe it's {"message": "No query results for model"}. Maybe it's {"error": "not found"}. Maybe it's {"success": false, "msg": "Invalid"} from that one controller someone wrote in a hurry. Maybe it's a full HTML error page, because the request didn't send the right Accept header.

Every one of those is a different contract. And the frontend has to handle all of them, usually with a growing pile of if (body.message || body.error || body.msg).

The fix isn't fancy. Pick one error shape and make every failure use it.

Pick a shape and write it down

It doesn't have to be clever. It has to be the same every time.

{
  "error": {
    "code": "subscription_inactive",
    "message": "Your subscription isn't active.",
    "details": {},
    "request_id": "9f2c1e7a"
  }
}

Four fields, each with a job:

  • code is for machines. Short, stable, snake_case. The frontend switches on this.
  • message is for humans. You can reword it any time without breaking anything.
  • details holds the structured extras, like field-level validation errors.
  • request_id is what a user pastes into a support ticket so you can find the log line.

If you'd rather use a standard, RFC 9457 (Problem Details, the successor to RFC 7807) defines application/problem+json with type, title, status, detail, and instance, plus room for your own fields. That's a perfectly good choice. What matters is choosing one and sticking to it.

The code is the contract, the message isn't

If your React app does this, you've already lost:

if (error.message.includes('not active')) {
  showUpgradePrompt();
}

Somebody fixes a typo in the message, or adds translations, and the upgrade prompt silently stops showing. Nobody gets an error. The feature just quietly dies.

Messages change. Codes shouldn't. Treat a code like a public API: add new ones freely, never rename an old one.

Throw errors that already know their shape

For errors your app raises on purpose, give them their own exception. Laravel calls render() on an exception if it has one, so the exception can carry its own response:

namespace App\Exceptions;
 
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
 
class ApiException extends Exception
{
    public function __construct(
        public readonly string $errorCode,
        string $message,
        public readonly int $status = 400,
        public readonly array $details = [],
    ) {
        parent::__construct($message);
    }
 
    public function render(Request $request): JsonResponse
    {
        return response()->json([
            'error' => [
                'code' => $this->errorCode,
                'message' => $this->getMessage(),
                'details' => $this->details,
                'request_id' => $request->headers->get('X-Request-Id'),
            ],
        ], $this->status);
    }
}

Then in a controller or action:

if (! $account->subscriptionActive()) {
    throw new ApiException('subscription_inactive', "Your subscription isn't active.", 403);
}

No hand-built response()->json([...]) scattered across forty controllers, each with its own idea of what an error looks like.

The X-Request-Id header assumes you have middleware setting one. If you don't, that's worth fixing on its own.

Catch everything else in one place

Your own exceptions are the easy part. The rest come from the framework: validation, auth, missing models, rate limits, and the 500 you didn't see coming.

In Laravel 11 and up, that all lives in bootstrap/app.php:

use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
 
->withExceptions(function (Exceptions $exceptions) {
    $exceptions->render(function (Throwable $e, Request $request) {
        if (! $request->is('api/*')) {
            return null; // let web routes render normally
        }
 
        $headers = $e instanceof HttpExceptionInterface ? $e->getHeaders() : [];
 
        [$status, $code, $message, $details] = match (true) {
            $e instanceof ValidationException => [422, 'validation_failed', 'Some fields need attention.', $e->errors()],
            $e instanceof AuthenticationException => [401, 'unauthenticated', 'You need to log in.', []],
            $e instanceof HttpExceptionInterface => [
                $e->getStatusCode(),
                match ($e->getStatusCode()) {
                    403 => 'forbidden',
                    404 => 'not_found',
                    429 => 'rate_limited',
                    default => 'http_error',
                },
                Response::$statusTexts[$e->getStatusCode()] ?? 'Request failed.',
                [],
            ],
            default => [500, 'server_error', 'Something went wrong on our end.', []],
        };
 
        return response()->json([
            'error' => [
                'code' => $code,
                'message' => $message,
                'details' => $details,
                'request_id' => $request->headers->get('X-Request-Id'),
            ],
        ], $status, $headers);
    });
})

A few things worth knowing about how this plays out:

  • Exceptions with their own render() method, like ApiException, get handled before this callback runs.
  • By the time the callback sees it, Laravel has already turned a missing model into a 404 and a failed policy check into a 403, so those land in the HttpExceptionInterface branch.
  • Passing $e->getHeaders() through keeps things like Retry-After on a 429. Drop it and your rate limit responses lose the one header the client actually needed.
  • Rendering doesn't change reporting. Your 500s still get logged and sent to whatever error tracker you use.

Don't leak the stack trace to make it "helpful"

That default branch is doing real work. The raw exception message for a 500 is often a SQL error, a file path, or a connection string fragment. None of that belongs in a response body.

The user gets "Something went wrong on our end" and a request ID. You get the full exception in the logs, findable by that same ID. Everybody gets what they actually need.

And keep APP_DEBUG off in production. It exists to show you everything, which is exactly the problem.

Give the frontend one way to read it

Now the client can stop guessing. One fetch wrapper, one error class:

type ApiErrorBody = {
  code: string;
  message: string;
  details: Record<string, unknown>;
  request_id: string | null;
};
 
export class ApiError extends Error {
  constructor(public status: number, public body: ApiErrorBody) {
    super(body.message);
  }
}
 
function isApiErrorBody(value: unknown): value is { error: ApiErrorBody } {
  if (typeof value !== 'object' || value === null || !('error' in value)) return false;
  const error = (value as { error: unknown }).error;
  return typeof error === 'object' && error !== null && typeof (error as ApiErrorBody).code === 'string';
}
 
export async function api<T>(path: string, init: RequestInit = {}): Promise<T> {
  const res = await fetch(`/api${path}`, {
    ...init,
    headers: { Accept: 'application/json', ...(init.headers as Record<string, string>) },
  });
 
  if (res.ok) {
    return (res.status === 204 ? undefined : await res.json()) as T;
  }
 
  const body = await res.json().catch(() => null);
 
  if (isApiErrorBody(body)) {
    throw new ApiError(res.status, body.error);
  }
 
  throw new ApiError(res.status, {
    code: 'unexpected_response',
    message: `Request failed with status ${res.status}`,
    details: {},
    request_id: null,
  });
}

That last fallback matters more than it looks. Your app is not the only thing that can answer a request. A load balancer timing out, a proxy returning a 502, or a maintenance page can all send back HTML. The .catch(() => null) keeps that from turning into a confusing JSON parse error in the middle of your error handling.

Then the calling code reads like a decision instead of a guessing game:

try {
  await api('/subscriptions/upgrade', { method: 'POST' });
} catch (e) {
  if (!(e instanceof ApiError)) throw e;
 
  switch (e.body.code) {
    case 'validation_failed':
      setFieldErrors(e.body.details as Record<string, string[]>);
      break;
    case 'subscription_inactive':
      showUpgradePrompt();
      break;
    default:
      showToast(`Something went wrong. Reference: ${e.body.request_id ?? 'none'}`);
  }
}

Test the shape, not just the status

A status code assertion won't catch someone returning {"msg": "nope"} from a new endpoint. Assert the structure:

it('returns the standard error shape for a missing invoice', function () {
    $this->actingAs(User::factory()->create())
        ->getJson('/api/invoices/999999')
        ->assertNotFound()
        ->assertJsonStructure(['error' => ['code', 'message', 'details', 'request_id']])
        ->assertJsonPath('error.code', 'not_found');
});

Write one of these for validation, one for auth, one for a 404, and one for a domain error. Four tests, and the contract is enforced instead of hoped for.

The short version

  1. Pick one error shape for the whole API and write it down.
  2. Give every error a stable machine code. Never make clients parse the message.
  3. Let your own exceptions render themselves.
  4. Funnel framework errors through one handler so they match.
  5. Keep internals out of 500 responses. Hand back a request ID instead.
  6. Make the client handle non-JSON errors, because something upstream will send one.
  7. Test the shape, not just the status code.

Your happy path probably already has a nice, consistent shape. Your errors deserve the same treatment, because they're the responses the frontend has to be smartest about.