Under The Hood
backend nestjs NestJS 10+

Exception Filters: @Catch(), HttpException Normalization, and Error Boundaries

Last updated
Prerequisites:
NestJS ArgumentsHost
JavaScript Error and Exception Handling
  • nestjs
  • exception-filters
  • http-exception
  • error-handling
  • catch-decorator

Read at your depth

The practical view

Exception Filters catch unhandled exceptions across your application. Create one with `@Catch()` implementing `ExceptionFilter`: `catch(exception, host: ArgumentsHost)`. You extract `const ctx = host.switchToHttp()`, get `response` and `request`, and format a custom error response: `response.status(status).json({ ... })`. NestJS includes built-in classes like `NotFoundException`, `BadRequestException`, and `UnauthorizedException` inheriting from `HttpException`.

The same idea in other frameworks

nestjs equivalent
`@Catch()` implementing `ExceptionFilter` with `host.switchToHttp()`.

Legacy vs modern

Try-Catch Controller Boilerplate vs Centralized Exception Filter

Writing try/catch blocks in every controller leaks implementation details; an Exception Filter normalizes errors globally.

before → after
Manual Try-Catch in Controllers
try { await service.find(); } catch (err) { res.status(500).json({ err }); } // ❌ Leaks raw errors
Global All-Exceptions Filter
@Catch() export class AllExceptionsFilter implements ExceptionFilter { ... } // ✅ NEW: Centralized & sanitized

Interview gotchas

Context

Interviewers test your knowledge of global provider tokens vs `app.useGlobalFilters()`.

The mechanical answer

Register the filter in `AppModule` using the **`APP_FILTER`** token: ```typescript { provide: APP_FILTER, useClass: AllExceptionsFilter } ``` This ensures the filter is managed by the NestJS IoC container with full dependency injection support. Using `app.useGlobalFilters(new AllExceptionsFilter())` in `main.ts` prevents constructor dependency injection.

Trap

Never use `new Filter()` in `main.ts` if your filter requires injected services.

Under The Hood — a multi-depth technical interview hub.

Third-party licenses Press ⌘ K to search.