-
-
Notifications
You must be signed in to change notification settings - Fork 141
feat(server): rethrow handler plugin #1286
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. | ||
| ::: |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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), | ||
| }) | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| } | ||
| }) | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.