Exception Filters & Error Handling
Exception Filters & Error Handling
Things go wrong: a record is missing, input is bad, a third party times out. NestJS has a built-in exceptions layer that turns thrown errors into proper HTTP responses — and exception filters let you customise exactly how those responses look.
Built-in HTTP exceptions
Instead of crafting error responses by hand, throw one of NestJS's built-in exceptions. The framework catches it and sends the right status code and JSON body:
Common ones: BadRequestException (400), UnauthorizedException (401), ForbiddenException (403), NotFoundException (404), ConflictException (409), and InternalServerErrorException (500).
The base HttpException
For a custom status or body, throw HttpException directly:
throw from anywhere — a service, a pipe, a guard. The exceptions layer catches it at the boundary and formats the response. Your handler stays clean.
Writing an exception filter
An exception filter takes full control over the response for the exceptions it catches. Decorate it with @Catch() and implement catch(exception, host):
@Catch(HttpException) scopes the filter to a type; @Catch() with no argument catches everything, useful for a global safety net.
Applying filters
Summary
Throw built-in exceptions like NotFoundException (or HttpException for custom cases) and let the exceptions layer format the HTTP response. For full control, write an exception filter with @Catch() and catch(exception, host), then bind it per-route or globally. A global filter gives your API one consistent, safe error format. This completes the request lifecycle — last in this phase: custom decorators.