ExceptionFilter
Interface for filters that catch unhandled exceptions and craft the response.
Syntax
catch(exception: T, host: ArgumentsHost): void Parameters
| Name | Type | Required | Description |
|---|---|---|---|
exception | T | No | The thrown exception instance. |
host | ArgumentsHost | No | Accessor for the request and response objects. |
Returns
void — The filter writes the response itself.
Examples
import {
ExceptionFilter, Catch, ArgumentsHost, HttpException,
} from '@nestjs/common';
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const res = ctx.getResponse();
const status = exception.getStatus();
res.status(status).json({
statusCode: status,
message: exception.message,
timestamp: new Date().toISOString(),
});
}
}
Notes
Annotate the class with @Catch() to choose which exceptions it handles.
The filter is responsible for sending the response. Bind it with
@UseFilters() or app.useGlobalFilters().