intermediate
NestJS filters
Convert framework, HTTP, validation, and domain exceptions into consistent responses with enough operational context.
Exception filters catch thrown exceptions and map them to HTTP responses. `@Catch()` scopes which exception types a filter handles. A global filter in `main.ts` ensures consistent error shapes.
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
catch(exception: unknown, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const res = ctx.getResponse<Response>();
const status =
exception instanceof HttpException
? exception.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR;
const body =
exception instanceof HttpException
? exception.getResponse()
: { message: 'Internal server error' };
res.status(status).json(body);
}
}
Domain exceptions can extend `HttpException` or be mapped in a custom filter. Filters run after guards, interceptors, and pipes — they are the last line for response shaping on failure.
On interviews: filters versus Express error middleware, logging in filters versus interceptors, and preserving correlation IDs.
Common pitfalls: catching everything as 500, leaking stack traces, and different error shapes per module without a global filter.
The trade-off is balancing simplicity, performance, safety, and operability — name which axis you optimized and what cost you accepted.
Checklist:
- Register a global exception filter.
- Map domain errors to HTTP status codes.
- Log server errors with context; sanitize clients.
- Use @Catch for specialized exception types.