Kind: Class
Source: packages/core/exceptions/base-exception-filter.ts
Part of: Core
BaseExceptionFilter is NestJS’s default HTTP exception handling foundation. It converts HttpException instances and compatible HTTP error objects into framework responses, while safely returning a generic 500 response and logging unexpected errors.
Implements: ExceptionFilter
Methods
| Method | Signature | Returns |
|---|---|---|
catch | catch(exception: T, host: ArgumentsHost) | void |
handleUnknownError | `handleUnknownError(exception: T, host: ArgumentsHost, applicationRef: AbstractHttpAdapter | HttpServer)` |
isExceptionObject | isExceptionObject(err: any) | err is Error |
isHttpError | isHttpError(err: any) | err is { statusCode: number; message: string } |
Properties
| Property | Type |
|---|---|
httpAdapterHost | HttpAdapterHost |
Where it refuses work
BaseExceptionFilterstops the work with an early return when!(exception instanceof HttpException).
Diagram
mermaidgraph LR A[Thrown exception] --> B[BaseExceptionFilter.catch] B --> C{HttpException?} C -->|Yes| D[Extract status and response body] D --> E[Send response through HTTP adapter] C -->|No| F[handleUnknownError] F --> G{HTTP-style error object?} G -->|Yes| H[Use statusCode and message] G -->|No| I[Return generic 500 response] H --> E I --> E
Usage
tsimport { ArgumentsHost, Catch } from '@nestjs/common';
import { BaseExceptionFilter } from '@nestjs/core';
@Catch()
export class AllExceptionsFilter extends BaseExceptionFilter {
catch(exception: unknown, host: ArgumentsHost) {
// Add custom logging, metrics, or tracing here.
console.error('Unhandled exception:', exception);
// Preserve Nest's standard HTTP exception behavior.
super.catch(exception, host);
}
}
// Register the filter globally:
// app.useGlobalFilters(new AllExceptionsFilter());
AI Coding Instructions
- Extend
BaseExceptionFilterwhen adding cross-cutting exception behavior while retaining NestJS’s default HTTP response handling. - Always call
super.catch(exception, host)unless the custom filter intentionally replaces the complete response flow. - Use
handleUnknownError()for non-HttpExceptionerrors; it handles safe 500 responses and error logging. - Avoid exposing raw unknown error messages or stack traces in HTTP responses; rely on the base filter’s generic internal-error behavior.
- Ensure custom filters are registered through
app.useGlobalFilters()or theAPP_FILTERprovider token.
Relationships
- IMPORTS →
ArgumentsHost - IMPORTS →
ExceptionFilter - IMPORTS →
HttpException - IMPORTS →
HttpServer - IMPORTS →
HttpStatus - IMPORTS →
Inject - IMPORTS →
IntrinsicException - IMPORTS →
Logger - IMPORTS →
Optional - IMPORTS →
isObject
Was this page helpful?