Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/content/.vitepress/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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' },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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' {
/**
Expand All @@ -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],
}),
Expand Down
38 changes: 38 additions & 0 deletions apps/content/docs/plugins/rethrow-handler.md
Original file line number Diff line number Diff line change
@@ -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.
:::
1 change: 1 addition & 0 deletions packages/server/src/plugins/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
195 changes: 195 additions & 0 deletions packages/server/src/plugins/rethrow.test.ts
Original file line number Diff line number Diff line change
@@ -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),
})
})
})
88 changes: 88 additions & 0 deletions packages/server/src/plugins/rethrow.ts
Original file line number Diff line number Diff line change
@@ -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<T extends Context> {
/**
* 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<boolean, [error: ThrowableError, options: StandardHandlerInterceptorOptions<T>]>
}

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<T extends Context> implements StandardHandlerPlugin<T> {
private readonly filter: experimental_RethrowHandlerPluginOptions<T>['filter']

CONTEXT_SYMBOL = Symbol('ORPC_RETHROW_HANDLER_PLUGIN_CONTEXT')

constructor(options: experimental_RethrowHandlerPluginOptions<T>) {
this.filter = options.filter
}

init(options: StandardHandlerOptions<T>): 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
}
})
}
}
Loading