Skip to content
Backend & APIChapter 25 / 57Intermediate6 min read

Error Handling & Error Envelope

Keep your API error response format consistent, use the right status codes, never leak internals in a 500, and write the real cause to the server log.

On this page

1. What is this practice?

An envelope is a fixed wrapper. In this course the shape for Next.js is:

json
{ "error": "Human readable message", "code": "OPTIONAL_MACHINE_CODE" }

The shape can be anything, like { message, errors, success }. What matters is that there is one across the whole app, and that message strings are constants so tests assert the same constant the route returns.

2. Why does it matter?

One endpoint returns { message }, another returns { err }, and a third returns { success: false } with status 200. The frontend developer writes a different if for every call and forgets one. The user gets a blank screen instead of "Something went wrong".

The security bug is more dangerous. A catch block sent error.message to the client. Now the response says duplicate key value violates unique constraint "users_email_key". The attacker learns the table name, the column, and also that this email is registered.

Without the ruleWith the rule
Every endpoint has its own error shapeOne envelope, the client handles it in one place
Status 200 even on an errorThe status code itself tells what happened
A 500 leaks a SQL error or stack traceA generic message, the details go to the log
A login error reveals that the account existsAuth errors hide whether an account exists
An empty catch swallows the errorThe error is either handled or logged and passed up

3. When to follow it

LevelHow importantWhy
Learning projectLearn to keep status codes rightThis is where you understand the difference between 401, 403, 404 and 422
Production codeA mustThe client, tests and monitoring all run on this shape
Senior levelDesign the envelope and the error classesA new endpoint gives the right errors automatically

When to learn it: when your frontend first needs to show an API's error.

4. Bad vs good code

Bad: its own way everywhere

ts
export async function POST(request: Request) {
  try {
    const body = await request.json();
    const invite = await acceptInvite(body.token);
    return Response.json({ success: true, invite });
  } catch (e) {
    const error = e as Error;
    return Response.json({ success: false, message: error.message, stack: error.stack });
  }
}

The status is always 200. An expired invite and a database crash look the same. The stack trace and the internal message go straight to the browser.

Good: error classes and one mapper

File lib/errors/errors.ts:

ts
import { NextResponse } from "next/server";

import { GENERIC_ERROR } from "./errors.types";

export class AppError extends Error {
  constructor(
    message: string,
    readonly status: number,
    readonly code: string,
  ) {
    super(message);
  }
}

export function toErrorResponse(error: unknown, scope: string) {
  if (error instanceof AppError) {
    return NextResponse.json({ error: error.message, code: error.code }, { status: error.status });
  }

  console.error(`[${scope}]`, error);

  return NextResponse.json({ error: GENERIC_ERROR }, { status: 500 });
}

The service throws an AppError in expected situations:

ts
export async function acceptInvite(token: string) {
  const invite = await findInviteByTokenHash(hashToken(token));
  if (!invite) {
    throw new AppError(INVITE_MESSAGES.notFound, 404, "INVITE_NOT_FOUND");
  }
  if (invite.expiresAt < new Date()) {
    throw new AppError(INVITE_MESSAGES.expired, 410, "INVITE_EXPIRED");
  }

  return markInviteAccepted(invite.id);
}

The handler only maps:

ts
export async function POST(request: Request) {
  const parsed = acceptInviteSchema.safeParse(await request.json().catch(() => null));
  if (!parsed.success) {
    return NextResponse.json({ error: INVITE_MESSAGES.invalidInput }, { status: 422 });
  }

  try {
    const invite = await acceptInvite(parsed.data.token);
    return NextResponse.json({ invite });
  } catch (error) {
    return toErrorResponse(error, "invites:accept");
  }
}

What is the difference?

ThingBad codeGood code
StatusAlways 200404, 410, 422, 500, whichever is true
Shapesuccess, message, stackerror and code
Unexpected errorMessage and stack go to the clientA generic message, the cause is logged with [scope]
MessagesInline stringsConstants, and tests use them too

A small map of status codes

StatusWhen
400The request itself is broken, like invalid JSON
401The caller is not authenticated
403Authenticated but not allowed
404The resource was not found
409A conflict, like a duplicate or out of stock
422The shape is fine, but the values fail validation
429Rate limited, with a Retry-After header
500A truly unexpected failure
502 / 503A problem with an upstream service or configuration

5. How to apply it

The journey of an error
The service throws a typed error in expected situations
Do not catch unexpected errors, let them go up
The handler builds the envelope with a mapper
A known error goes out with its own status
Everything else is a 500, the cause goes to the log, the client gets a generic message

6. Exceptions and common mistakes

Sometimes a 404 is returned on purpose instead of a 403, so an attacker cannot tell that the resource exists. That is fine if it is done deliberately and the team knows. In login and "forgot password" too, keep the response the same whether the account exists or not.

Mistake: Leaving a catch block empty

Why? The error disappears, the user sees a false success, and there is no trace in the logs.

Better: Either handle the error and give the right response, or log it and throw it up.

Mistake: Sending error.message in a 500 response

Why? Internal details of the database, file paths and libraries reach the attacker.

Better: Give the client a generic constant, and log the real error on the server with a scope prefix.

Mistake: Returning 401 for a signed in user without permission

Why? The client thinks the session expired and keeps sending the user back to the login page.

Better: Use 401 only for missing or invalid credentials, and 403 when permission is missing.

Mistake: Logging and rethrowing at every layer

Why? The same error shows up three or four times in the log and the real place is hard to find.

Better: Log the error in one place, usually where it is turned into a response.

7. What to learn before and after

Final quick revision

CheckQuestion
EnvelopeIs every error in one shape?
StatusDoes the status code tell the truth?
LeakDoes a 500 ever send error.message or a stack?
LogIs an unexpected error logged with [scope]?
ConstantsAre messages constants that tests use too?
AuthDo auth errors hide whether an account exists?