Skip to content

BaseRpcExceptionFilter

reference
1 min readUpdated

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

MethodSignatureReturns
catchcatch(exception: T, host: ArgumentsHost)Observable<R>
handleUnknownErrorhandleUnknownError(exception: T, status: string)void
isErrorisError(exception: any)exception is Error

Where it refuses work

  • BaseRpcExceptionFilter stops the work with an early return when !(exception instanceof RpcException).

Diagram

mermaid
graph 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

ts
import { 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 RpcException for 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 on message or stack properties when handling values that may not be native Error instances.
  • 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?

Download as PDF
BaseRpcExceptionFilter — NestJS head-to-head