Phase 13 · Lesson 05

Global ApiExceptionFilter

≈ 3 min core reading · 624 source/companion words
Learning contract

What you should be able to do after this

  • Explain Global ApiExceptionFilter without relying on framework buzzwords.
  • Connect the lesson to the phase outcome: Create a stable application error model that separates expected domain/transport failures from unexpected faults and keeps diagnostics observable.
  • Reproduce the relevant behavior and verify it with evidence.
  • Diagnose at least one representative failure instead of guessing.
Figure 13.5 — TaskFlow boundary map
failure occurs
typed/application error
exception mapping
structured log
safe HTTP error
frontend recovery
This lesson belongs to Phase 13. Keep the full request/data path visible even when today's code changes only one box.
Instructor workflow: predict first → implement the smallest slice → run it → inspect evidence → break one assumption → diagnose → explain it back. Do not copy the whole code block before understanding the first failing boundary.

Global ApiExceptionFilter Build a Fastify-compatible catch-all filter with HttpAdapterHost and safe normalization

Phase 13 - Professional Error Handling Volume 04 - Professional Backend

Architecture milestone exception

↓

normalize

↓

log

↓

httpAdapter.reply

Phase 13 creates one professional exception boundary and a correlation story that spans client response and server logs.

Build the global ApiExceptionFilter The filter is intentionally a translation boundary. It receives unknown exceptions, decides which failures are safe and known, creates one public envelope, logs diagnostics, then writes the response through NestJS HttpAdapterHost.

import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus, Logger, } from "@nestjs/common"; import { HttpAdapterHost } from "@nestjs/core"; import { FastifyRequest } from "fastify"; import { Prisma } from "../../generated/prisma/client"; import { ApiErrorResponse } from "./api-error-response";

Code
@Catch()
export class ApiExceptionFilter implements ExceptionFilter {
private readonly logger = new Logger(ApiExceptionFilter.name);

constructor(private readonly httpAdapterHost: HttpAdapterHost) {}

Code
catch(exception: unknown, host: ArgumentsHost): void {
const { httpAdapter } = this.httpAdapterHost;
const context = host.switchToHttp();
const request = context.getRequest<FastifyRequest>();
const response = context.getResponse();
Code
const result = this.normalize(exception);
const requestId = String(request.id);
const path = httpAdapter.getRequestUrl(request);

const body: ApiErrorResponse = { statusCode: result.statusCode, code: result.code, message: result.message, requestId, timestamp: new Date().toISOString(), path, ...(result.details ? { details: result.details } : {}), };

if (result.statusCode >= 500) { this.logger.error("Unhandled request failure", { requestId,

method: request.method, path, statusCode: result.statusCode, exceptionName: exception instanceof Error ? exception.name : typeof exception, stack: exception instanceof Error ? exception.stack : undefined, }); } else { this.logger.warn("Request rejected", { requestId, method: request.method, path, statusCode: result.statusCode, code: result.code, }); }

httpAdapter.reply(response, body, result.statusCode); }

private normalize(exception: unknown): { statusCode: number; code: string; message: string; details?: string[] | Record<string, unknown>; } { if (exception instanceof HttpException) { return this.fromHttpException(exception); }

if (exception instanceof Prisma.PrismaClientKnownRequestError) { return this.fromPrismaError(exception); }

return { statusCode: HttpStatus.INTERNAL_SERVER_ERROR, code: "INTERNAL_ERROR", message: "An unexpected server error occurred.", }; }

private fromHttpException(exception: HttpException) {

Code
const statusCode = exception.getStatus();
const response = exception.getResponse();

if (typeof response === "string") { return { statusCode, code: this.defaultCode(statusCode), message: response, }; }

if (response && typeof response === "object") { const body = response as { code?: unknown; message?: unknown; };

if (Array.isArray(body.message)) { return { statusCode, code: typeof body.code === "string" ? body.code : this.defaultCode(statusCode), message: "Request validation failed.", details: body.message.map(String), }; }

if (typeof body.message === "string") { return { statusCode, code: typeof body.code === "string" ? body.code : this.defaultCode(statusCode), message: body.message, }; } }

return { statusCode, code: this.defaultCode(statusCode),

Code
message: "Request failed.",
};
}

private fromPrismaError( exception: Prisma.PrismaClientKnownRequestError, ) { switch (exception.code) { case "P2002": return { statusCode: HttpStatus.CONFLICT, code: "UNIQUE_CONSTRAINT_CONFLICT", message: "A resource with the same unique value already exists.", };

case "P2003": return { statusCode: HttpStatus.CONFLICT, code: "RELATION_CONFLICT", message: "The operation conflicts with an existing relationship.", };

case "P2025": return { statusCode: HttpStatus.NOT_FOUND, code: "RESOURCE_NOT_FOUND", message: "The requested resource was not found.", };

default: return { statusCode: HttpStatus.INTERNAL_SERVER_ERROR, code: "DATABASE_ERROR", message: "A database operation failed.", }; } }

private defaultCode(statusCode: number): string { switch (statusCode) { case HttpStatus.BAD_REQUEST: return "BAD_REQUEST";

case HttpStatus.UNAUTHORIZED: return "UNAUTHORIZED"; case HttpStatus.FORBIDDEN: return "FORBIDDEN"; case HttpStatus.NOT_FOUND: return "NOT_FOUND"; case HttpStatus.CONFLICT: return "CONFLICT"; default: return `HTTP_${statusCode}`; } } }

Three normalization paths Input exception Normalization path Public result

HttpException Preserve status, code/message where 4xx/5xx contract supplied

Prisma known request error Translate known P-codes 409/404 or sanitized DB failure

Anything else Treat as unexpected fault 500 INTERNAL_ERROR

Validation details without framework coupling The filter does not need to know that Zod created the validation error. It inspects the HttpException response. If the message is an array, TaskFlow uses a stable top-level message and moves those strings into details.

if (Array.isArray(body.message)) { return { statusCode, code: "BAD_REQUEST", message: "Request validation failed.", details: body.message.map(String), }; }

Adapter-agnostic response writing httpAdapter.reply( response, body, result.statusCode, );

Why this matters

Earlier NestJS examples often use Express Response.json(). Our course explicitly chose Fastify in Phase 04, so the exception boundary should not quietly depend on Express-only APIs.

Executable lesson studio · pagination

Now turn the explanation into engineering skill.

Global ApiExceptionFilter matters because it changes a real boundary in TaskFlow. The goal is to understand the inputs, owner, observable output, and failure modes before adding more abstraction.

By the end, you should be able to

  • Explain Global ApiExceptionFilter in terms of concrete inputs, ownership, outputs, and evidence.
  • Implement or reproduce the smallest TaskFlow slice that demonstrates this pagination concept.
  • Diagnose one representative pagination failure using observable evidence instead of trial-and-error.
Figure 13.5B — Mental model
query parameters
validated filter/sort
stable query
page/cursor
response metadata
Read left-to-right while implementing. When debugging, walk right-to-left until the first observed fact differs from your prediction.
Code-along sequence

One coherent change at a time

  1. 01

    Restate the goal of “Global ApiExceptionFilter” as one observable behavior. Write the success signal before touching code.

  2. 02

    Trace the boundary map: query parameters → validated filter/sort → stable query → page/cursor → response metadata. Mark the one boundary this lesson changes.

  3. 03

    Inspect the current repository state and record the exact files, route, table, or runtime involved. Avoid creating an abstraction before you can name the existing owner.

  4. 04

    Implement the smallest vertical slice. Add one coherent change, run the narrowest verification command, and read the output before continuing.

  5. 05

    Connect the slice to TaskFlow’s phase artifact: Error taxonomy + NestJS mapping layer/filters + structured error response with request IDs.. Verify behavior from the outside as a user or API client would.

  6. 06

    Create one controlled failure that is safe to reproduce. Predict the symptom first, capture evidence, locate the earliest broken boundary, then fix only that cause.

  7. 07

    Close the reference and rebuild or explain the core change from memory. Record what you would monitor or test before trusting the same change in production.

tsA stable cursor needs a stable ordering
orderBy: [{ createdAt: "desc" }, { id: "desc" }],
take: limit + 1,
where: cursor ? {
  OR: [
    { createdAt: { lt: cursor.createdAt } },
    { createdAt: cursor.createdAt, id: { lt: cursor.id } },
  ],
} : undefined

Do not copy this as a finished answer. Predict what each boundary does, type the smallest useful slice, run it, then compare the result with your prediction.

Verification

Prove the happy path

  1. Run the narrowest relevant command or request and require a clean exit/status.
  2. Inspect the boundary-specific evidence: terminal output, Network panel, database row/query plan, test report, container health, or deployment logs.
  3. Repeat the behavior once after the change so a one-off cached or stale result cannot masquerade as success.
Break it on purpose

Build debugging memory

  1. Returning raw exception messages/stacks
  2. Change one assumption in the pagination example—identity, input, configuration, ordering, connectivity, or state—and predict the exact symptom before running it.
SymptomInvestigation path
Expected result does not appear

Return to the nearest observable boundary: input, network, process log, database, or rendered UI. Compare actual evidence with the predicted path.

A shortcut appears to fix it

Change one variable at a time and reproduce the original failure after the fix; otherwise you have correlation, not diagnosis.

Closed-reference challenge

Can you transfer the idea?

Without copying the final source, create a second small scenario that applies “Global ApiExceptionFilter” to a different TaskFlow resource or input. Write the acceptance criteria first, implement it, and provide the evidence that each criterion is satisfied.

Explain-back

Answer these without reopening the solution

  1. What problem does Global ApiExceptionFilter solve in TaskFlow, and what would be observably wrong without it?
  2. Which part of the pagination boundary owns the decision, and which neighboring layer must not own it?
  3. What evidence proves the happy path instead of merely suggesting it worked?
  4. Name one realistic failure or abuse case and the first place you would inspect.
  5. If requirements doubled tomorrow, which part of this design should stay stable and which part is allowed to change?
Lesson studio

Turn the reading into skill

01

Do it

Trigger each error class intentionally and verify both client-safe response and server diagnostic context.

Use the smallest change that demonstrates this lesson. Stop after it works and capture evidence.
02

Break it safely

Returning raw exception messages/stacks

Predict the symptom before causing the failure. Then locate the earliest boundary where reality diverges from expectation.
03

Explain it back

Why does this responsibility live here, what input does it trust, what output proves success, and what would go wrong if another layer owned it?

If your explanation is vague, repeat the boundary trace before moving on.
Exit ticket

Before marking complete

Close the reference. Reproduce the core idea from memory or explain the exact request/data flow aloud. Then check your diff or notes for accidental shortcuts that bypass validation, authorization, error handling, or verification earned in earlier phases.