From b2bc7a12c0c0df24c532d41c7f16fbe3c3d4f1d7 Mon Sep 17 00:00:00 2001 From: unnoq Date: Wed, 10 Dec 2025 15:10:19 +0700 Subject: [PATCH 1/2] feat(server): rethrow handler plugin --- apps/content/.vitepress/config.ts | 1 + .../implement-contract-in-nest.md | 15 +- apps/content/docs/plugins/rethrow-handler.md | 38 ++++ packages/server/src/plugins/index.ts | 1 + packages/server/src/plugins/rethrow.test.ts | 195 ++++++++++++++++++ packages/server/src/plugins/rethrow.ts | 88 ++++++++ 6 files changed, 336 insertions(+), 2 deletions(-) create mode 100644 apps/content/docs/plugins/rethrow-handler.md create mode 100644 packages/server/src/plugins/rethrow.test.ts create mode 100644 packages/server/src/plugins/rethrow.ts diff --git a/apps/content/.vitepress/config.ts b/apps/content/.vitepress/config.ts index c174dc910..1f3e9fc94 100644 --- a/apps/content/.vitepress/config.ts +++ b/apps/content/.vitepress/config.ts @@ -150,6 +150,7 @@ export default withMermaid(defineConfig({ { text: 'Batch Requests', link: '/docs/plugins/batch-requests' }, { text: 'Client Retry', link: '/docs/plugins/client-retry' }, { text: 'Retry After', link: '/docs/plugins/retry-after' }, + { text: 'Rethrow Handler', link: '/docs/plugins/rethrow-handler' }, { text: 'Compression', link: '/docs/plugins/compression' }, { text: 'Body Limit', link: '/docs/plugins/body-limit' }, { text: 'Simple CSRF Protection', link: '/docs/plugins/simple-csrf-protection' }, diff --git a/apps/content/docs/openapi/integrations/implement-contract-in-nest.md b/apps/content/docs/openapi/integrations/implement-contract-in-nest.md index 40412e48a..494e688e9 100644 --- a/apps/content/docs/openapi/integrations/implement-contract-in-nest.md +++ b/apps/content/docs/openapi/integrations/implement-contract-in-nest.md @@ -222,8 +222,11 @@ Configure the `@orpc/nest` module by importing `ORPCModule` in your NestJS appli ```ts import { Module } from '@nestjs/common' import { REQUEST } from '@nestjs/core' -import { onError, ORPCModule } from '@orpc/nest' +import { onError, ORPCError, ORPCModule } from '@orpc/nest' import { Request } from 'express' // if you use express adapter +import { + experimental_RethrowHandlerPlugin as RethrowHandlerPlugin, +} from '@orpc/server/plugins' declare module '@orpc/nest' { /** @@ -246,7 +249,15 @@ declare module '@orpc/nest' { context: { request }, // oRPC context, accessible from middlewares, etc. eventIteratorKeepAliveInterval: 5000, // 5 seconds customJsonSerializers: [], - plugins: [], // most oRPC plugins are compatible + plugins: [ + new RethrowHandlerPlugin({ + filter: (error) => { + // Rethrow all non-ORPCError errors + // This allows unhandled exceptions to bubble up to NestJS global exception filters + return !(error instanceof ORPCError) + }, + }) + ], // most oRPC plugins are compatible }), inject: [REQUEST], }), diff --git a/apps/content/docs/plugins/rethrow-handler.md b/apps/content/docs/plugins/rethrow-handler.md new file mode 100644 index 000000000..6e0d796f3 --- /dev/null +++ b/apps/content/docs/plugins/rethrow-handler.md @@ -0,0 +1,38 @@ +--- +title: Rethrow Handler Plugin +description: A plugin to catch and rethrow specific errors during request handling instead of handling them in the oRPC error flow. +--- + +# Rethrow Handler Plugin + +The `RethrowHandlerPlugin` allows you to catch and rethrow specific errors that occur during request handling. This is particularly useful when your framework has its own error handling mechanism (e.g., global exception filters in NestJS, error middleware in Express) and you want certain errors to be processed by that mechanism instead of being handled by the oRPC error handling flow. + +## Usage + +```ts twoslash +import { ORPCError } from '@orpc/server' +import { RPCHandler } from '@orpc/server/fetch' +import { router } from './shared/planet' + +// ---cut--- +import { + experimental_RethrowHandlerPlugin as RethrowHandlerPlugin, +} from '@orpc/server/plugins' + +const handler = new RPCHandler(router, { + plugins: [ + new RethrowHandlerPlugin({ + // Decide which errors should be rethrown. + filter: (error) => { + // Example: Rethrow all non-ORPCError errors + // This allows unhandled exceptions to bubble up to your framework + return !(error instanceof ORPCError) + }, + }), + ], +}) +``` + +::: info +The `handler` can be any supported oRPC handler, such as [RPCHandler](/docs/rpc-handler), [OpenAPIHandler](/docs/openapi/openapi-handler), or another custom handler. +::: diff --git a/packages/server/src/plugins/index.ts b/packages/server/src/plugins/index.ts index f48a3ecb3..7938b00f4 100644 --- a/packages/server/src/plugins/index.ts +++ b/packages/server/src/plugins/index.ts @@ -2,5 +2,6 @@ export * from './batch' export * from './cors' export * from './request-headers' export * from './response-headers' +export * from './rethrow' export * from './simple-csrf-protection' export * from './strict-get-method' diff --git a/packages/server/src/plugins/rethrow.test.ts b/packages/server/src/plugins/rethrow.test.ts new file mode 100644 index 000000000..669485323 --- /dev/null +++ b/packages/server/src/plugins/rethrow.test.ts @@ -0,0 +1,195 @@ +import { ORPCError } from '@orpc/client' +import { RPCHandler } from '../adapters/fetch' +import { os } from '../builder' +import { experimental_RethrowHandlerPlugin as RethrowHandlerPlugin } from './rethrow' + +beforeEach(() => { + vi.clearAllMocks() +}) + +describe('rethrowHandlerPlugin', () => { + it('should rethrow errors when filter returns true', async () => { + class CustomError extends Error { + constructor(message: string, public readonly code: number) { + super(message) + this.name = 'CustomError' + } + } + + const customError = new CustomError('Error with code', 42) + + const handler = new RPCHandler({ + ping: os.handler(() => { + throw customError + }), + }, { + strictGetMethodPluginEnabled: false, + plugins: [ + new RethrowHandlerPlugin({ + filter: () => true, // Always rethrow + }), + ], + }) + + await expect( + handler.handle(new Request('http://localhost/ping', { + method: 'POST', + body: JSON.stringify({}), + headers: { 'Content-Type': 'application/json' }, + })), + ).rejects.toThrow(customError) + }) + + it('should not rethrow errors when filter returns false', async () => { + const customError = new Error('Custom error that should not be rethrown') + + const handler = new RPCHandler({ + ping: os.handler(() => { + throw customError + }), + }, { + strictGetMethodPluginEnabled: false, + plugins: [ + new RethrowHandlerPlugin({ + filter: () => false, // Never rethrow + }), + ], + }) + + await expect( + handler.handle(new Request('http://localhost/ping', { + method: 'POST', + body: JSON.stringify({}), + headers: { 'Content-Type': 'application/json' }, + })), + ).resolves.toEqual({ matched: true, response: expect.toSatisfy((response: Response) => response.status === 500) }) + }) + + it('should rethrow non-ORPCError errors and handle ORPCError normally', async () => { + const handler = new RPCHandler({ + throwCustom: os.handler(() => { + throw new Error('Custom error') + }), + throwORPC: os.handler(() => { + throw new ORPCError('BAD_REQUEST', { message: 'ORPC error' }) + }), + }, { + strictGetMethodPluginEnabled: false, + plugins: [ + new RethrowHandlerPlugin({ + filter: error => !(error instanceof ORPCError), + }), + ], + }) + + // Non-ORPCError should be rethrown + await expect( + handler.handle(new Request('http://localhost/throwCustom', { + method: 'POST', + body: JSON.stringify({}), + headers: { 'Content-Type': 'application/json' }, + })), + ).rejects.toThrow('Custom error') + + // ORPCError should be handled normally (not rethrown) + await expect( + handler.handle(new Request('http://localhost/throwORPC', { + method: 'POST', + body: JSON.stringify({}), + headers: { 'Content-Type': 'application/json' }, + })), + ).resolves.toEqual({ matched: true, response: expect.toSatisfy((response: Response) => response.status === 400) }) + }) + + it('should pass error and options to filter function', async () => { + const filter = vi.fn(() => false) + const thrownError = new Error('Test error') + + const handler = new RPCHandler({ + ping: os.handler(() => { + throw thrownError + }), + }, { + strictGetMethodPluginEnabled: false, + plugins: [ + new RethrowHandlerPlugin({ filter }), + ], + }) + + await handler.handle(new Request('http://localhost/ping', { + method: 'POST', + body: JSON.stringify({}), + headers: { 'Content-Type': 'application/json' }, + })) + + expect(filter).toHaveBeenCalledTimes(1) + expect(filter).toHaveBeenCalledWith( + thrownError, + expect.objectContaining({ + request: expect.objectContaining({ + method: 'POST', + }), + context: expect.any(Object), + }), + ) + }) + + it('should work normally without errors being thrown', async () => { + const handler = new RPCHandler({ + ping: os.handler(() => 'pong'), + }, { + strictGetMethodPluginEnabled: false, + plugins: [ + new RethrowHandlerPlugin({ + filter: () => true, + }), + ], + }) + + await expect( + handler.handle(new Request('http://localhost/ping', { + method: 'POST', + body: JSON.stringify({}), + headers: { 'Content-Type': 'application/json' }, + })), + ).resolves.toEqual({ + matched: true, + response: expect.toSatisfy((response: Response) => response.status === 200), + }) + }) + + it('should response error if other plugins or interceptors corrupt the context', async () => { + const handler = new RPCHandler({ + ping: os.handler(() => 'pong'), + }, { + strictGetMethodPluginEnabled: false, + plugins: [ + new RethrowHandlerPlugin({ + filter: () => true, + }), + { + init(options) { + options.rootInterceptors?.push(async (options) => { + // Corrupt the context + return options.next({ + ...options, + context: {}, + }) + }) + }, + }, + ], + }) + + await expect( + handler.handle(new Request('http://localhost/ping', { + method: 'POST', + body: JSON.stringify({}), + headers: { 'Content-Type': 'application/json' }, + })), + ).resolves.toEqual({ + matched: true, + response: expect.toSatisfy((response: Response) => response.status === 500), + }) + }) +}) diff --git a/packages/server/src/plugins/rethrow.ts b/packages/server/src/plugins/rethrow.ts new file mode 100644 index 000000000..217d92832 --- /dev/null +++ b/packages/server/src/plugins/rethrow.ts @@ -0,0 +1,88 @@ +import type { ThrowableError, Value } from '@orpc/shared' +import type { StandardHandlerInterceptorOptions, StandardHandlerOptions, StandardHandlerPlugin } from '../adapters/standard' +import type { Context } from '../context' +import { value } from '@orpc/shared' + +export interface experimental_RethrowHandlerPluginOptions { + /** + * Decide which errors should be rethrown. + * + * @example + * ```ts + * const rethrowPlugin = new RethrowHandlerPlugin({ + * filter: (error) => { + * // Rethrow all non-ORPCError errors + * return !(error instanceof ORPCError) + * } + * } + * ``` + */ + filter: Value]> +} + +interface RethrowHandlerPluginContext { + error?: { value: ThrowableError } +} + +/** + * The plugin allows you to catch and rethrow specific errors that occur during request handling. + * This is particularly useful when your framework has its own error handling mechanism + * (e.g., global exception filters in NestJS, error middleware in Express) + * and you want certain errors to be processed by that mechanism instead of being handled by the + * oRPC error handling flow. + * + * @see {@link https://orpc.dev/docs/plugins/rethrow-handler Rethrow Handler Plugin Docs} + */ +export class experimental_RethrowHandlerPlugin implements StandardHandlerPlugin { + private readonly filter: experimental_RethrowHandlerPluginOptions['filter'] + + CONTEXT_SYMBOL = Symbol('ORPC_RETHROW_HANDLER_PLUGIN_CONTEXT') + + constructor(options: experimental_RethrowHandlerPluginOptions) { + this.filter = options.filter + } + + init(options: StandardHandlerOptions): void { + options.rootInterceptors ??= [] + options.interceptors ??= [] + + options.rootInterceptors.push(async (options) => { + const pluginContext: RethrowHandlerPluginContext = {} + + const result = await options.next({ + ...options, + context: { + ...options.context, + [this.CONTEXT_SYMBOL]: pluginContext, + }, + }) + + if (pluginContext.error) { + throw pluginContext.error.value + } + + return result + }) + + options.interceptors.unshift(async (options) => { + const pluginContext = options.context[this.CONTEXT_SYMBOL] as RethrowHandlerPluginContext | undefined + + if (!pluginContext) { + throw new TypeError('[RethrowHandlerPlugin] Rethrow handler context has been corrupted or modified by another plugin or interceptor') + } + + try { + // await is important here to catch both sync and async errors + return await options.next() + } + catch (error) { + if (value(this.filter, error as ThrowableError, options)) { + pluginContext.error = { value: error as ThrowableError } + return { matched: false, response: undefined } + } + + throw error + } + }) + } +} From 7437ea4098749dc77584ca8687ee86a923d33a41 Mon Sep 17 00:00:00 2001 From: unnoq Date: Wed, 10 Dec 2025 18:44:19 +0700 Subject: [PATCH 2/2] Update packages/server/src/plugins/rethrow.ts Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- packages/server/src/plugins/rethrow.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/server/src/plugins/rethrow.ts b/packages/server/src/plugins/rethrow.ts index 217d92832..ab2139c0a 100644 --- a/packages/server/src/plugins/rethrow.ts +++ b/packages/server/src/plugins/rethrow.ts @@ -14,7 +14,7 @@ export interface experimental_RethrowHandlerPluginOptions { * // Rethrow all non-ORPCError errors * return !(error instanceof ORPCError) * } - * } + * }) * ``` */ filter: Value]>