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
`@Catch()` implementing `ExceptionFilter` with `host.switchToHttp()`.Spring Boot `@ControllerAdvice` with `@ExceptionHandler` methods.FastAPI `@app.exception_handler(CustomException)` decorators.Express 4-parameter error middleware `(err, req, res, next)`.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.
try { await service.find(); } catch (err) { res.status(500).json({ err }); } // ❌ Leaks raw errors@Catch() export class AllExceptionsFilter implements ExceptionFilter { ... } // ✅ NEW: Centralized & sanitizedInterview 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.
Context
Checks precision regarding exception inheritance filtering.
The mechanical answer
`@Catch(HttpException)` will **only catch exceptions that inherit from `HttpException`** (like `NotFoundException`, `BadRequestException`). Unhandled native errors (e.g. `TypeError`, `DatabaseConnectionError`) will bypass the filter. `@Catch()` (with no arguments) acts as an **All-Exceptions catch-all** that intercepts every single error thrown in the app.
Trap
If using `@Catch(HttpException)`, unhandled database crashes will bypass your filter and be handled by the default fallback.