Lesson 12 / 34
Exception Handling
Throw built-in HTTP exceptions and format errors consistently with a global exception filter.
Built-in exceptions
NestJS provides BadRequestException, NotFoundException, UnauthorizedException, etc. that automatically set the right HTTP status.
import { NotFoundException, BadRequestException } from '@nestjs/common';
@Get(':id')
findOne(@Param('id') id: string) {
const user = this.usersService.findOne(id);
if (!user) {
throw new NotFoundException(`User ${id} not found`);
}
return user;
}Global exception filter
Implement ExceptionFilter to catch and format errors globally across your app.
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
catch(exception: unknown, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse();
const status = exception instanceof HttpException ? exception.getStatus() : 500;
response.status(status).json({
statusCode: status,
message: exception instanceof Error ? exception.message : 'Internal error'
});
}
}
// app.useGlobalFilters(new AllExceptionsFilter());Throwing HTTP exceptions
Throw a built-in exception and Nest builds the response.
NotFoundExceptionmaps to status 404.- The message you pass becomes the
messagefield.
import { Controller, Get, NotFoundException, Param } from '@nestjs/common';
@Controller('books')
export class BooksController {
@Get(':id')
find(@Param('id') id: string) {
throw new NotFoundException(`Book ${id} not found`);
}
}
Output:
{"message":"Book 5 not found","error":"Not Found","statusCode":404}Quick check
Quick check: What does `@Catch()` with no arguments on an exception filter catch?
- Only HttpException
- Every thrown exception
- Only validation errors
Answer
Every thrown exception — An empty `@Catch()` is a catch-all filter for any exception type.