Skip to content
NestPath

Exercises — Exception Filters

Covers: the inconsistent-defaults problem, HttpException hierarchy, ErrorResponse shape design, @Catch(HttpException) filter, @Catch() all-exceptions filter, normalizing exception.getResponse(), global registration (useGlobalFilters vs APP_FILTER), scoping with @UseFilters, custom domain exceptions, log-vs-leak discipline.


Part A — Concept Checks (closed book)

  1. Name the three different default error shapes NestJS produces (thrown HttpException, ValidationPipe failure, unhandled crash) and what's inconsistent between them.
  2. Where do exception filters sit in the lifecycle, and from which stages can they catch exceptions?
  3. Draw (or list) 6 built-in exceptions from the HttpException hierarchy with their status codes.
  4. exception.getResponse() can return two different types — which, produced by what kind of throw? How does the lesson's filter normalize them?
  5. What does @Catch(HttpException) catch vs @Catch() with no argument? Which one must be a superset?
  6. Why does the lesson recommend logging the full stack server-side but sending a sanitized 500 to the client? What specifically must never leak?
  7. useGlobalFilters(new AllExceptionsFilter()) vs the APP_FILTER provider — what capability does only the second one give you, and why?
  8. If you register multiple global filters, which catches first — first or last registered?
  9. What is ArgumentsHost and what do switchToHttp().getRequest()/getResponse() give you?
  10. Why does TaskNotFoundException extends NotFoundException require zero changes to your existing filter? Name the principle.
  11. Give one legitimate reason to scope a filter to a single controller instead of globally.
  12. In the standard ErrorResponse interface, why is message always a string and details always an array-or-absent?

Part B — Guided Exercises

B1. Build the standard error envelope

  1. Create src/common/interfaces/error-response.interface.ts with statusCode, error, message, details?, timestamp, path.
  2. Implement HttpExceptionFilter (@Catch(HttpException)) exactly handling: - string responses (throw new HttpException('x', 400)) - object responses with string message - object responses with array message (ValidationPipe) → message: 'Validation failed', array into details - a getErrorName(status) map
  3. Implement AllExceptionsFilter (@Catch()) that: - delegates known HttpExceptions to the same formatting - for unknown errors: logs method, url, and full stack via Logger, returns generic 500 "An unexpected error occurred"
  4. Register AllExceptionsFilter globally in main.ts.

Checkpoint — verify all four scenarios return the SAME shape: - GET /tasks/999 → 404 with path: "/tasks/999" and timestamp - POST /tasks invalid body → 400 with details array - GET /tasks/abc → 400 (ParseIntPipe message preserved) - Temporarily add throw new Error('boom') in the service → client gets generic 500, console gets full stack. Remove the throw after.

B2. Migrate to DI-aware registration

  1. Move registration from main.ts to AppModule via APP_FILTER.
  2. Prove DI works: inject a Logger or a small ErrorMetricsService (counts errors by status code in memory) into the filter — impossible with new.
  3. Expose GET /stats/errors returning the counts. Watch it increment as you trigger errors.

B3. Custom domain exceptions

  1. Create TaskNotFoundException(taskId) and NoteNotFoundException(noteId) extending NotFoundException.
  2. Create DuplicateTaskTitleException(title) extending ConflictException (pairs with Module 01 C2).
  3. Replace generic throws in services. Confirm responses are identical in shape — only messages changed.

Part C — Independent Challenges

C1. Error codes for the frontend

Extend the envelope with a machine-readable errorCode (e.g., TASK_NOT_FOUND, VALIDATION_FAILED, DUPLICATE_TITLE, INTERNAL). Design: custom exceptions carry their code (hint: pass an object to super() or add a public property); the filter extracts it, falling back to a sensible default. Frontend can now switch(errorCode) instead of parsing English.

C2. Webhook-shaped errors

A hypothetical payment provider requires errors from POST /webhooks/payments in its format: { "ok": false, "reason": "<string>" }, always HTTP 200. Build a WebhookExceptionFilter and scope it with @UseFilters to only that controller. Verify the rest of the API still uses your standard envelope.

C3. Environment-aware leakage

Using ConfigService (or process.env.NODE_ENV), make the 500 handler include stack in the response only when NODE_ENV !== 'production'. This requires DI-aware registration — explain why in a comment.


Part D — Debug Drills

D1

ts
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) { /* formats nicely */ }
}
// main.ts
app.useGlobalFilters(new HttpExceptionFilter());

Symptom: a TypeError in the service returns the raw ugly default 500, not your format. Why, and two possible fixes?

D2

ts
const errorResponse = { ... };
response.json(errorResponse);

Symptom: every error arrives at the client as HTTP 200 with an error body. One missing call — what is it?

D3

ts
app.useGlobalFilters(new AllExceptionsFilter());
// AND in AppModule:
providers: [{ provide: APP_FILTER, useClass: AllExceptionsFilter }]

What happens here — crash, double-formatting, or something subtler? What does the lesson say to do?

D4

ts
} else if (typeof exceptionResponse === 'object') {
  message = exceptionResponse.message;   // no Array.isArray check
}

POST /tasks with 3 invalid fields — what does the client's message field literally contain now, and which frontend bug from the lesson's intro does this resurrect?

D5

ts
catch(exception: unknown, host: ArgumentsHost) {
  const status = (exception as HttpException).getStatus();
  ...
}

This @Catch() filter itself crashes on a plain Error. What happens when an exception filter throws, and what's the correct status-resolution pattern?


Part E — Prediction Drills

Assume the full lesson setup (AllExceptionsFilter global, validation from Module 02). Predict exact status + body shape:

  1. DELETE /tasks/999
  2. POST /tasks body {} — how many entries in details?
  3. Service code: throw new HttpException('Teapot mode', 418) — what's error in the response given the lesson's getErrorName map?
  4. Guard (Module 05 preview) throws UnauthorizedException('No token') — does this filter catch it even though the controller never ran?
  5. The filter's own catch method throws — what does the client receive?

Part F — Stretch Goals

  1. Add the request-ID (Module 06 preview): if req['requestId'] exists, include it in every error response.
  2. Split into two filters as the lesson describes (business vs crash) with warn vs error log levels; write down when this split is worth it.
  3. Research HttpAdapterHost — rewrite AllExceptionsFilter platform-agnostically (works for Express and Fastify).

Self-Assessment Checklist

  • Every error my API emits — 400/401/403/404/409/500 — has one identical shape
  • I can write both @Catch(HttpException) and @Catch() filters from memory
  • I know the string/object/array normalization dance for getResponse()
  • I can register a filter DI-aware and have injected something into it
  • Nothing internal (stack, file paths) reaches clients on a 500, but my logs have everything
  • I've built and scoped a controller-specific filter

Answers & Hints

A1: HttpException → {statusCode, message: string, error}; ValidationPipe → message: string[]; crash → {statusCode: 500, message: "Internal server error"} with no error field. message flip-flops between string and array; fields differ; no timestamp/path anywhere.

A2: Last stage before the response; catches exceptions from middleware, guards, interceptors, pipes, controllers, services — anywhere in the pipeline.

A3: BadRequest 400, Unauthorized 401, Forbidden 403, NotFound 404, MethodNotAllowed 405, Conflict 409, Gone 410, PayloadTooLarge 413, UnprocessableEntity 422, InternalServerError 500 (any six).

A4: A string (from new HttpException('msg', code)) or an object (standard exceptions and ValidationPipe). Normalize: string → message; object with array message → 'Validation failed' + details; object with string message → that message; fallback text otherwise.

A5: @Catch(HttpException) catches HttpException + subclasses only. Bare @Catch() catches everything — it must handle the HttpException cases too if it's your only filter.

A6: Stack traces reveal file paths, library versions, internal logic — reconnaissance for attackers. Log everything server-side; client gets a generic message.

A7: APP_FILTER constructs the filter inside the DI container → constructor injection works (ConfigService, Logger, etc.). new gives you a dependency-less instance.

A8: Last registered catches first (stack behavior).

A9: An abstraction over the execution context (HTTP/WS/RPC); switchToHttp() narrows it and exposes the raw Express Request/Response.

A10: Polymorphism — @Catch(HttpException)/@Catch() matches by instanceof, and the subclass IS-A NotFoundException IS-A HttpException.

A11: A route must obey an external error contract (e.g., webhook providers) different from your API standard.

A12: Predictability: the frontend can always render message directly and iterate details if present — no typeof checks ever.

D1: The filter only catches HttpException; plain TypeError falls through to Nest's built-in default. Fix: use @Catch() AllExceptionsFilter, or register both filters.

D2: response.status(status) — Express defaults to 200 when you skip it.

D3: Double registration — Nest will run filters from both registrations; at best redundant, at worst confusing precedence. The lesson: pick one; if using APP_FILTER, delete the useGlobalFilters line.

D4: message becomes the raw array again — resurrecting the typeof error.message === 'string' ? ... : ... frontend hack the whole module exists to kill.

D5: If a filter throws, Nest falls back to the default handler → client gets the ugly generic 500. Correct pattern: const status = exception instanceof HttpException ? exception.getStatus() : 500;.

E1: 404 envelope, message: "Task with id 999 not found", path: "/tasks/999". E2: 400, message: "Validation failed"; details for title (isString, isNotEmpty, maxLength won't all fire — expect ~2 per field for missing values → typically 4 entries for two required fields; verify empirically!). E3: 418 isn't in the map → error: "Error" fallback; message "Teapot mode". E4: Yes — filters catch exceptions from guards too; 401 envelope with your shape. E5: Nest's default: plain {"statusCode":500,"message":"Internal server error"} — your formatting is gone, which is why filters must be defensive.