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)
- Name the three different default error shapes NestJS produces (thrown HttpException, ValidationPipe failure, unhandled crash) and what's inconsistent between them.
- Where do exception filters sit in the lifecycle, and from which stages can they catch exceptions?
- Draw (or list) 6 built-in exceptions from the
HttpExceptionhierarchy with their status codes. exception.getResponse()can return two different types — which, produced by what kind of throw? How does the lesson's filter normalize them?- What does
@Catch(HttpException)catch vs@Catch()with no argument? Which one must be a superset? - Why does the lesson recommend logging the full stack server-side but sending a sanitized 500 to the client? What specifically must never leak?
useGlobalFilters(new AllExceptionsFilter())vs theAPP_FILTERprovider — what capability does only the second one give you, and why?- If you register multiple global filters, which catches first — first or last registered?
- What is
ArgumentsHostand what doswitchToHttp().getRequest()/getResponse()give you? - Why does
TaskNotFoundException extends NotFoundExceptionrequire zero changes to your existing filter? Name the principle. - Give one legitimate reason to scope a filter to a single controller instead of globally.
- In the standard
ErrorResponseinterface, why ismessagealways a string anddetailsalways an array-or-absent?
Part B — Guided Exercises
B1. Build the standard error envelope
- Create
src/common/interfaces/error-response.interface.tswithstatusCode, error, message, details?, timestamp, path. - Implement
HttpExceptionFilter(@Catch(HttpException)) exactly handling: - string responses (throw new HttpException('x', 400)) - object responses with stringmessage- object responses with arraymessage(ValidationPipe) →message: 'Validation failed', array intodetails- agetErrorName(status)map - Implement
AllExceptionsFilter(@Catch()) that: - delegates knownHttpExceptions to the same formatting - for unknown errors: logs method, url, and full stack viaLogger, returns generic 500"An unexpected error occurred" - Register
AllExceptionsFilterglobally inmain.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
- Move registration from
main.tstoAppModuleviaAPP_FILTER. - Prove DI works: inject a
Loggeror a smallErrorMetricsService(counts errors by status code in memory) into the filter — impossible withnew. - Expose
GET /stats/errorsreturning the counts. Watch it increment as you trigger errors.
B3. Custom domain exceptions
- Create
TaskNotFoundException(taskId)andNoteNotFoundException(noteId)extendingNotFoundException. - Create
DuplicateTaskTitleException(title)extendingConflictException(pairs with Module 01 C2). - 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
@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
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
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
} 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
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:
DELETE /tasks/999POST /tasksbody{}— how many entries indetails?- Service code:
throw new HttpException('Teapot mode', 418)— what'serrorin the response given the lesson'sgetErrorNamemap? - Guard (Module 05 preview) throws
UnauthorizedException('No token')— does this filter catch it even though the controller never ran? - The filter's own
catchmethod throws — what does the client receive?
Part F — Stretch Goals
- Add the request-ID (Module 06 preview): if
req['requestId']exists, include it in every error response. - Split into two filters as the lesson describes (business vs crash) with
warnvserrorlog levels; write down when this split is worth it. - Research
HttpAdapterHost— rewriteAllExceptionsFilterplatform-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.
