Kind: Class
Source: packages/microservices/exceptions/base-rpc-exception-filter.ts
Part of: Microservices
BaseRpcExceptionFilter is the default foundation for handling exceptions thrown by NestJS microservice RPC handlers. It converts known RpcException instances into error observables and safely maps unknown errors to a standardized internal-error response while logging unexpected failures.
Implements: RpcExceptionFilter
Methods
| Method | Signature | Returns |
|---|---|---|
catch | catch(exception: T, host: ArgumentsHost) | Observable<R> |
handleUnknownError | handleUnknownError(exception: T, status: string) | void |
isError | isError(exception: any) | exception is Error |
Where it refuses work
BaseRpcExceptionFilterstops the work with an early return when!(exception instanceof RpcException).
Diagram
mermaidgraph LR A[RPC Handler throws exception] --> B[BaseRpcExceptionFilter.catch] B --> C{Is RpcException?} C -- Yes --> D[Extract exception error payload] D --> E[Return error Observable] C -- No --> F[handleUnknownError] F --> G{Is Error instance?} G -- Yes --> H[Log unexpected error] G -- No --> I[Create unknown error response] H --> I I --> E
Usage
tsimport { Catch, ArgumentsHost } from '@nestjs/common';
import {
BaseRpcExceptionFilter,
RpcException,
} from '@nestjs/microservices';
import { Observable } from 'rxjs';
@Catch()
export class RpcExceptionFilter extends BaseRpcExceptionFilter {
catch(exception: unknown, host: ArgumentsHost): Observable<unknown> {
// Add custom logging, metrics, or error normalization here.
return super.catch(exception, host);
}
}
// In an RPC controller:
throw new RpcException({
status: 'VALIDATION_ERROR',
message: 'The provided email address is invalid.',
});
AI Coding Instructions
- Extend this class when custom RPC exception behavior is needed; delegate to
super.catch()unless intentionally replacing the default mapping. - Throw
RpcExceptionfor expected, client-safe microservice errors so its payload is preserved in the RPC response. - Do not expose raw unknown error messages or stack traces to RPC consumers; use
handleUnknownError()for safe fallback responses. - Use
isError()before relying onmessageorstackproperties when handling values that may not be nativeErrorinstances. - Ensure custom filters are registered with the relevant microservice/controller context so they run for RPC transport requests.
Relationships
- IMPORTS →
ArgumentsHost - IMPORTS →
IntrinsicException - IMPORTS →
Logger - IMPORTS →
RpcExceptionFilter - IMPORTS →
isObject - IMPORTS →
MESSAGES
Was this page helpful?