Exception Filters
In Express you wrote one error-handling middleware and threw errors with a status property. Nest has the same idea built in: throw an HttpException anywhere — in a service, guard or pipe — and the global exception layer turns it into a JSON response. When you need a different format, you write an exception filter.
Built-in HTTP exceptions
| Exception | Status |
|---|---|
BadRequestException |
400 |
UnauthorizedException |
401 |
ForbiddenException |
403 |
NotFoundException |
404 |
ConflictException |
409 |
UnprocessableEntityException |
422 |
PayloadTooLargeException |
413 |
InternalServerErrorException |
500 |
ServiceUnavailableException |
503 |
@Get(':id')
async findOne(@Param('id', ParseIntPipe) id: number) {
const cat = await this.catsService.findOne(id);
if (!cat) throw new NotFoundException(`Cat ${id} not found`);
return cat;
}
@Post()
async create(@Body() dto: CreateCatDto) {
if (await this.catsService.nameTaken(dto.name)) {
throw new ConflictException('A cat with that name already exists', { description: 'Duplicate name' });
}
return this.catsService.create(dto);
}
@Get('crash')
crash() {
throw new Error('database password is hunter2'); // NOT an HttpException
}curl localhost:3000/cats/9
curl -X POST localhost:3000/cats -H "Content-Type: application/json" -d '{"name":"Mochi","age":2}'
curl localhost:3000/cats/crash{"message":"Cat 9 not found","error":"Not Found","statusCode":404}
{"message":"A cat with that name already exists","error":"Duplicate name","statusCode":409}
{"statusCode":500,"message":"Internal server error"}
Unknown errors become a generic 500 — the message (and its secret) is logged on the server, not leaked to the client. That's the same rule you implemented by hand in the Express Error Handling lesson.
How the default response is built
Each built-in exception carries a status and a response body. If you pass a string, Nest builds { message, error, statusCode }; if you pass an object, that object becomes the body. This playground mimics the logic:
const STATUS_TEXT: Record<number, string> = { 400: 'Bad Request', 404: 'Not Found', 409: 'Conflict', 500: 'Internal Server Error' };
class HttpException extends Error {
constructor(readonly response: string | object, readonly status: number, readonly description?: string) {
super(typeof response === 'string' ? response : 'Http Exception');
}
getStatus() { return this.status; }
getResponse(): object {
if (typeof this.response === 'object') return this.response;
return { message: this.response, error: this.description ?? STATUS_TEXT[this.status], statusCode: this.status };
}
}
class NotFoundException extends HttpException {
constructor(message = 'Not Found') { super(message, 404); }
}
// The global exception layer: HttpExceptions are formatted, everything else is hidden.
function toResponse(err: unknown): { status: number; body: object } {
if (err instanceof HttpException) return { status: err.getStatus(), body: err.getResponse() };
console.log('[ExceptionsHandler]', (err as Error).message); // logged, not sent
return { status: 500, body: { statusCode: 500, message: 'Internal server error' } };
}
const thrown: unknown[] = [
new NotFoundException('Cat 9 not found'),
new HttpException('Name taken', 409, 'Duplicate name'),
new HttpException({ code: 'CAT_LOCKED', retryAfter: 30 }, 409),
new TypeError("Cannot read properties of undefined (reading 'age')"),
];
for (const err of thrown) {
const { status, body } = toResponse(err);
console.log(status, JSON.stringify(body));
}404 {"message":"Cat 9 not found","error":"Not Found","statusCode":404}
409 {"message":"Name taken","error":"Duplicate name","statusCode":409}
409 {"code":"CAT_LOCKED","retryAfter":30}
[ExceptionsHandler] Cannot read properties of undefined (reading 'age')
500 {"statusCode":500,"message":"Internal server error"}
Custom exceptions
Extend HttpException (or a subclass) to name your domain errors. Services stay readable and the status lives in one place:
export class InsufficientFundsException extends UnprocessableEntityException {
constructor(balance: number, required: number) {
super({ code: 'INSUFFICIENT_FUNDS', message: `Balance ${balance} is below ${required}` });
}
}Writing an exception filter
A filter takes full control of the response. @Catch(Type) chooses which exceptions it handles; @Catch() with no arguments catches everything. This one gives the whole API one error format, with a timestamp and the request path:
// src/common/all-exceptions.filter.ts
import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus, Logger } from '@nestjs/common';
import type { Request, Response } from 'express';
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
private readonly logger = new Logger('Exceptions');
catch(exception: unknown, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const res = ctx.getResponse<Response>();
const req = ctx.getRequest<Request>();
const status = exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;
const details = exception instanceof HttpException ? exception.getResponse() : 'Internal server error';
if (status >= 500) this.logger.error(exception);
res.status(status).json({
error: {
status,
path: req.originalUrl,
details,
timestamp: new Date().toISOString(),
},
});
}
}Register it globally — preferably as a provider, so it can use dependency injection:
// app.module.ts
import { APP_FILTER } from '@nestjs/core';
@Module({
providers: [{ provide: APP_FILTER, useClass: AllExceptionsFilter }],
})
export class AppModule {}curl localhost:3000/cats/9{"error":{"status":404,"path":"/cats/9","details":{"message":"Cat 9 not found","error":"Not Found","statusCode":404},"timestamp":"2025-06-01T09:30:00.000Z"}}
Choosing which filter runs
Filters can be bound to a method, a controller or globally (@UseFilters(...), app.useGlobalFilters(...), APP_FILTER). The most specific binding wins. Within a set of filters, the first whose @Catch() list matches the exception handles it:
class HttpException extends Error {}
class NotFoundException extends HttpException {}
class ValidationError extends Error {}
type Filter = { name: string; catches: Function[] }; // empty list = catch everything
function pickFilter(err: Error, filters: Filter[]) {
return filters.find((f) => f.catches.length === 0 || f.catches.some((t) => err instanceof t))?.name ?? 'built-in handler';
}
const methodFilters: Filter[] = [{ name: 'NotFoundFilter', catches: [NotFoundException] }];
const globalFilters: Filter[] = [
{ name: 'ValidationFilter', catches: [ValidationError] },
{ name: 'HttpFilter', catches: [HttpException] },
];
for (const err of [new NotFoundException(), new HttpException(), new ValidationError(), new RangeError()]) {
const chosen = pickFilter(err, methodFilters) !== 'built-in handler' ? pickFilter(err, methodFilters) : pickFilter(err, globalFilters);
console.log(err.constructor.name.padEnd(17), '->', chosen);
}NotFoundException -> NotFoundFilter
HttpException -> HttpFilter
ValidationError -> ValidationFilter
RangeError -> built-in handler
Tip:
NotFoundExceptionextendsHttpException, so@Catch(HttpException)also handles it. Catch the most specific class you mean, and keep one catch-all filter so nothing falls through to an inconsistent format.
Test yourself
What does Nest send for an uncaught new Error('secret') thrown in a service (default setup)?
- The error message with status 500
{"statusCode":500,"message":"Internal server error"}- A 400 response
- Nothing — the request hangs
Which decorator makes an exception filter handle every kind of exception?
- @Catch(Error) only
- @Catch() with no arguments
- @UseFilters()
- @All()
What status does throw new ConflictException('Email taken') produce?
- 400
- 403
- 409
- 422