Kind: Function
Source: packages/common/decorators/core/catch.decorator.ts
Part of: Common
Decorator that marks a class as a Nest exception filter. An exception filter handles exceptions thrown by or not handled by your application code.
The decorated class must implement the ExceptionFilter interface.
Catch() marks a class as a Nest exception filter, allowing it to intercept exceptions thrown during request processing. The decorated class must implement Nest's ExceptionFilter interface and can optionally target one or more specific exception types.
Signature
tsfunction Catch(exceptions: Array<Type<any> | Abstract<any>>): ClassDecorator
Parameters
| Name | Type |
|---|---|
exceptions | `Array<Type |
Returns: ClassDecorator
Diagram
mermaidgraph LR A[Request Handler] -->|throws exception| B[Nest Exception Layer] B --> C{Matching @Catch Filter?} C -->|Yes| D[Custom ExceptionFilter.catch] D --> E[Create HTTP Response] C -->|No| F[Default Nest Exception Handler]
Usage
tsimport {
ArgumentsHost,
Catch,
ExceptionFilter,
HttpException,
} from '@nestjs/common';
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost): void {
const response = host.switchToHttp().getResponse();
const request = host.switchToHttp().getRequest();
response.status(exception.getStatus()).json({
statusCode: exception.getStatus(),
path: request.url,
message: exception.message,
});
}
}
// Register globally:
// app.useGlobalFilters(new HttpExceptionFilter());
AI Coding Instructions
- Decorate exception filter classes with
@Catch(); pass exception constructors such asHttpExceptionto handle only matching errors. - Always implement the
ExceptionFilterinterface and provide acatch(exception, host)method. - Use
ArgumentsHostto select the active transport context, such ashost.switchToHttp()for HTTP requests. - Register filters globally with
app.useGlobalFilters(), at controller scope with@UseFilters(), or provide them through Nest dependency injection. - Avoid swallowing exceptions without sending or delegating an appropriate response for the active transport.
Used by
6 references from 6 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example.
Imported by (6)
UnauthorizedFilter—integration/graphql-code-first/src/common/filters/unauthorized.filter.ts:4HttpExceptionFilter—integration/inspector/src/common/filters/http-exception.filter.ts:8RequestFilter—integration/websockets/src/request.filter.ts:4HttpExceptionFilter—sample/01-cats-app/src/common/filters/http-exception.filter.ts:8ExceptionFilter—sample/03-microservices/src/common/filters/rpc-exception.filter.ts:5HttpExceptionFilter—sample/36-hmr-esm/src/common/filters/http-exception.filter.ts:8
Was this page helpful?