In a NestJS 12 microservice, why does a NotFoundException thrown in a @MessagePattern() handler reach the caller as 'Internal server error'?
answer
- HTTP exceptions mean nothing here
- the base RPC exception filter
- RpcException with a string or object
- filters return an Observable
- events have no reply
basics
~10 sMessage handlers are served by Nest's base RPC exception filter, which only understands RpcException. Any other error, NotFoundException included, is replaced by { status: 'error', message: 'Internal server error' }. Throw RpcException instead.
solid answer
~50 sA message has no HTTP status line, so Nest's microservice layer ignores `HttpException` semantics. Its base filter, `BaseRpcExceptionFilter`, turns `new RpcException('Stock record not found')` into `{ status: 'error', message: 'Stock record not found' }`, passes an object given to `RpcException` through as is, and replaces anything else with `{ status: 'error', message: 'Internal server error' }`; it logs unknown errors, but skips Nest's own HTTP exceptions, so a `NotFoundException`'s message is lost without a log line. On the caller, the `send()` Observable errors with that plain object, not an `Error`. Custom handling goes in a class implementing `RpcExceptionFilter`, whose `catch()` must return an Observable such as `throwError(() => ...)`, or in one extending `BaseRpcExceptionFilter`. Two edges: an `@EventPattern()` handler has no response stream, so its errors never reach the producer, and on gRPC a plain `RpcException` arrives as `UNKNOWN` unless you use Nest 12's `GrpcExceptionFilter` with exceptions such as `GrpcNotFoundException`.
code
typescript · 17 linesimport { Controller } from '@nestjs/common';
import { MessagePattern, Payload, RpcException } from '@nestjs/microservices';
@Controller()
export class InventoryController {
private readonly stock = new Map<string, number>([['SKU-1', 3]]);
@MessagePattern({ cmd: 'check_stock' })
checkStock(@Payload('sku') sku: string) {
const available = this.stock.get(sku);
if (available === undefined) {
// the caller's send() errors with this object, unchanged
throw new RpcException({ code: 'NO_SKU', message: `Stock record not found: ${sku}` });
}
return { sku, available };
}
}go deeper
Recall that message handlers throw RpcException rather than HTTP exceptions, and that the caller receives an error object, not a status code.
Explain what the base RPC filter returns for a string, for an object and for any other error, and why a custom RpcExceptionFilter's catch() returns an Observable.
Diagnose the 'Internal server error' symptom from HTTP exceptions in handlers, design structured RpcException payloads a gateway can map to HTTP statuses, and plan for event errors that never reach the producer.
Agree an error contract across services: which codes an RpcException carries, where they turn into HTTP statuses, and whether gRPC services adopt Nest 12's status-specific exceptions.
## No status codes on the wire Over HTTP, Nest turns a thrown `HttpException` such as `NotFoundException` into a status line and a JSON body. A message handler has no status line: its error travels back to the caller as data through the transport. Nest therefore runs message handlers through a different exception layer, built on `BaseRpcExceptionFilter` from `@nestjs/microservices`, and that layer recognises one exception class: `RpcException`. ## What the base RPC filter does The base filter decides what the caller's `send()` Observable errors with: | Thrown in the handler | What the caller receives | Logged by Nest | |---|---|---| | `new RpcException('Stock record not found')` | `{ status: 'error', message: 'Stock record not found' }` | no | | `new RpcException({ code: 'NO_SKU', message: 'Stock record not found' })` | that object, as is | no | | `new NotFoundException('Stock record not found')` | `{ status: 'error', message: 'Internal server error' }` | no, HTTP exceptions are skipped | | any other error | `{ status: 'error', message: 'Internal server error' }` | yes | That third row is the question's symptom. `NotFoundException` is an HTTP concept, so the RPC layer treats it as an unknown error and hides its details behind a generic message. Worse, Nest's built-in HTTP exceptions are marked as intrinsic, which the base RPC filter does not log, so the real message appears neither on the caller nor in the consumer's log. On the calling side, the error is a deserialized **plain object**, not an `Error` instance, so `err instanceof Error` is false and there is no stack. Read `err.message` and any fields you put in the object. ## Throwing RpcException well - Pass a string for a simple message, or an object to send structured details such as a machine-readable `code`; Nest returns the object unchanged. - Throw it from guards and pipes too. A guard that returns `false` already becomes `RpcException('Forbidden resource')`, and `ValidationPipe` can be told to throw RPC errors with `exceptionFactory: (errors) => new RpcException(errors)`. - Keep payloads serializable, because the error crosses the transport as data. ## Tracing the symptom When a caller reports "Internal server error" from a message handler, work through it in order: 1. Find what the handler, its guards or its pipes throw. An `HttpException` subclass is the usual culprit, often from shared code written for HTTP controllers. 2. Check the consumer's log. An unknown error such as a `TypeError` is logged there; a built-in HTTP exception is not, which is why this bug hides so well. 3. Replace the throw with an `RpcException`, or add a filter that converts the HTTP exception at the message controller. ## Writing an RPC exception filter Custom handling follows the HTTP filter model with one difference: a class implementing `RpcExceptionFilter` must return an **Observable** from `catch()`, normally `throwError(() => ...)`. To add behaviour and then fall back to the defaults, extend `BaseRpcExceptionFilter` and call `super.catch(exception, host)`. ```ts @Catch(RpcException) export class StockErrorsFilter implements RpcExceptionFilter<RpcException> { catch(exception: RpcException, host: ArgumentsHost): Observable<never> { return throwError(() => exception.getError()); } } ``` Bind it with `@UseFilters()` on a method or controller, or globally with `useGlobalFilters()` on the microservice. In a hybrid app, global filters registered on the HTTP application reach the connected microservice only with `inheritAppConfig`. ## Receiving the error in an HTTP gateway When the order service calls inventory from an HTTP controller, rethrowing the caller's error object unchanged produces a 500, because the HTTP layer does not recognise a plain object either. Map it at the boundary instead: catch the error, inspect its `code` or `message`, and throw the matching `HttpException`, so a missing stock record becomes a 404 for the HTTP client. ## Two edges: events and gRPC - **Event handlers.** An `@EventPattern()` handler has no response stream, so its errors never reach the producer, even when a filter rethrows them. Handle them inside the handler or the filter, for example by logging, retrying or parking the event. - **gRPC.** A plain `RpcException` carries no gRPC status code, so a gRPC client sees `UNKNOWN` for every failure. Nest 12 adds status-specific exceptions such as `GrpcNotFoundException` and `GrpcInvalidArgumentException`, plus a generic `GrpcException` taking a `GrpcStatus`, and a `GrpcExceptionFilter` that maps them to proper gRPC errors. Register it with `app.useGlobalFilters(new GrpcExceptionFilter())`, and a missing record arrives as `NOT_FOUND`.
- In NestJS, what does the producer learn when an @EventPattern() handler throws?Nothing. An event handler has no response stream, so there is no channel to carry the error back, and even an error that a filter rethrows for an event handler never reaches the producer. Handle it on the consumer: log it, retry it, or park the event, and monitor the consumer's logs.
- How does a NestJS 12 gRPC handler return NOT_FOUND instead of UNKNOWN?Throw a status-specific exception such as `GrpcNotFoundException('Stock record not found')`, or `new GrpcException(message, GrpcStatus.NOT_FOUND)`, and register `GrpcExceptionFilter` with `app.useGlobalFilters(new GrpcExceptionFilter())`. Nest 11 shipped neither the filter nor these exceptions, and a plain `RpcException` carries no gRPC status code, so its failures reach gRPC clients as `UNKNOWN`.
- Why is the error a NestJS send() caller receives not an instance of Error?The error crosses the transport as serialized data, so the caller rebuilds a plain object such as `{ status: 'error', message: '...' }` and the `send()` Observable errors with it. It has no prototype chain and no stack, so `instanceof Error` checks fail; read its `message` and any custom fields, and convert it to an `HttpException` at an HTTP boundary.
- Throwing NotFoundException in a message handler sends a 404 to the caller.
- RpcException has a built-in status code field, just like HttpException.
- A custom RpcExceptionFilter can return a plain value from catch().
- An @EventPattern() handler's error is reported back to the emitting service.
- On gRPC, a plain RpcException is mapped to the right status code automatically.
Assumes NestJS 12: GrpcExceptionFilter and the status-specific gRPC exceptions are new in 12, while the RpcException handling is not among the 11 to 12 changes.