Skip to content
Closed
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
17 changes: 17 additions & 0 deletions apps/content/docs/openapi/handler.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,23 @@ const handler = new OpenAPIHandler(router, {
})
```

:::tip
Use `encodeError` to respond with an `ORPCError`, encoded the way procedure errors are. For example, to answer unmatched requests with a `NOT_FOUND` error:

```ts
;async ({ next, encodeError }) => {
const result = await next()

if (!result.matched) {
return { matched: true, response: await encodeError(new ORPCError('NOT_FOUND')) }
}

return result
}
```

:::

### Interceptors

These interceptors run only for matched requests, after routing and before error handling, and can use `ORPCError` for [typesafe errors](/docs/error-handling#orpcerror-compatibility). Use them when you need access to the matched procedure.
Expand Down
17 changes: 17 additions & 0 deletions apps/content/docs/rpc/handler.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,23 @@ const handler = new RPCHandler(router, {
})
```

:::tip
Use `encodeError` to respond with an `ORPCError`, encoded the way procedure errors are. For example, to answer unmatched requests with a `NOT_FOUND` error:

```ts
;async ({ next, encodeError }) => {
const result = await next()

if (!result.matched) {
return { matched: true, response: await encodeError(new ORPCError('NOT_FOUND')) }
}

return result
}
```

:::

### Interceptors

These interceptors run only for matched requests, after routing and before error handling, and can use `ORPCError` for [typesafe errors](/docs/error-handling#orpcerror-compatibility). Use them when you need access to the matched procedure.
Expand Down
5 changes: 5 additions & 0 deletions packages/node/src/tmp-file-upload-handler-plugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ describe('tmpFileUploadHandlerPlugin', () => {
await interceptor({
context: {},
prefix: undefined,
encodeError: vi.fn(),
request: {
method: 'POST',
url: '/upload',
Expand Down Expand Up @@ -589,6 +590,7 @@ describe('tmpFileUploadHandlerPlugin', () => {
const result = await interceptor({
context: {},
prefix: undefined,
encodeError: vi.fn(),
request: {
method: 'POST',
url: '/upload',
Expand Down Expand Up @@ -1092,6 +1094,7 @@ describe('tmpFileUploadHandlerPlugin', () => {
await plugin.init({}).routingInterceptors![0]!({
context: {},
prefix: undefined,
encodeError: vi.fn(),
request: {
method: 'POST',
url: '/upload',
Expand Down Expand Up @@ -1572,6 +1575,7 @@ describe('tmpFileUploadHandlerPlugin', () => {
await interceptor({
context: options.context,
prefix: undefined,
encodeError: vi.fn(),
request: {
method: 'POST',
url: '/upload',
Expand Down Expand Up @@ -1673,6 +1677,7 @@ describe('tmpFileUploadHandlerPlugin', () => {
const interceptorOptions = {
context: {},
prefix: undefined,
encodeError: vi.fn(),
request: {
method: 'POST',
url: '/upload',
Expand Down
9 changes: 8 additions & 1 deletion packages/server/src/adapters/standard-peer/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,10 @@ describe('createStandardPeerRequestHandler', () => {
})

it('returns 404 response when no procedure matched', async () => {
const notFound = { status: 404, headers: {}, body: 'encoded' }
const handler = {
handle: vi.fn(async () => ({ matched: false, response: undefined })),
encodeError: vi.fn(() => notFound),
} as any

const handleRequest = createStandardPeerRequestHandler(handler, { context: { context: true } })
Expand All @@ -53,13 +55,17 @@ describe('createStandardPeerRequestHandler', () => {
signal: new AbortController().signal,
})

expect(result).toEqual({ status: 404, headers: {}, body: 'No procedure matched' })
expect(result).toBe(notFound)
expect(handler.encodeError).toHaveBeenCalledWith(
expect.objectContaining({ code: 'NOT_FOUND', message: 'No procedure matched' }),
)
expect(handler.handle).toHaveBeenCalledTimes(1)
})

it('context fallback to empty object when it undefined', async () => {
const handler = {
handle: vi.fn(async () => ({ matched: false, response: undefined })),
encodeError: vi.fn(),
} as any

const handleRequest = createStandardPeerRequestHandler(handler, {})
Expand All @@ -80,6 +86,7 @@ describe('createStandardPeerRequestHandler', () => {
it('forwards a context function unresolved so the handler resolves it after its prefix check', async () => {
const handler = {
handle: vi.fn(async () => ({ matched: false, response: undefined })),
encodeError: vi.fn(),
} as any

const context = vi.fn(() => ({ db: 'postgres' }))
Expand Down
7 changes: 5 additions & 2 deletions packages/server/src/adapters/standard-peer/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ import type { StandardLazyRequest, StandardResponse } from '@standard-server/cor

import type { Context } from '../../context'
import type { FriendlyStandardHandlerHandleOptions, StandardHandler } from '../standard/index'
import { resolveFriendlyStandardHandlerHandleOptions } from '../standard/index'
import {
createNoProcedureMatchedError,
resolveFriendlyStandardHandlerHandleOptions,
} from '../standard/index'

export function createStandardPeerRequestHandler<T extends Context>(
handler: StandardHandler<T>,
Expand All @@ -13,6 +16,6 @@ export function createStandardPeerRequestHandler<T extends Context>(
request,
resolveFriendlyStandardHandlerHandleOptions(options),
)
return response ?? { status: 404, headers: {}, body: 'No procedure matched' }
return response ?? handler.encodeError(createNoProcedureMatchedError())
}
}
7 changes: 1 addition & 6 deletions packages/server/src/adapters/standard/codec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,5 @@ export interface StandardHandlerCodec<T extends Context> {
options: ResolvedStandardHandlerHandleOptions<T>,
): Promisable<StandardResponse>

encodeError(
error: AnyORPCError,
procedure: AnyProcedure,
path: string[],
options: ResolvedStandardHandlerHandleOptions<T>,
): Promisable<StandardResponse>
encodeError(error: AnyORPCError): Promisable<StandardResponse>
}
8 changes: 2 additions & 6 deletions packages/server/src/adapters/standard/handler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ describe('standardHandler', () => {
expect(routingInterceptor).toHaveBeenCalledTimes(1)
expect(routingInterceptor).toHaveBeenCalledWith({
next: expect.any(Function),
encodeError: expect.any(Function),
request,
context: OPTIONS.context,
prefix: OPTIONS.prefix,
Expand Down Expand Up @@ -433,12 +434,7 @@ describe('standardHandler', () => {
matched: true,
response: { status: 502, headers: {}, body: 'bad gateway' },
})
expect(codec.encodeError).toHaveBeenCalledWith(
procedureError,
expect.anything(),
['ping'],
OPTIONS,
)
expect(codec.encodeError).toHaveBeenCalledWith(procedureError)
})

it('reconciles errors thrown outside the procedure call with the procedure error map', async () => {
Expand Down
17 changes: 12 additions & 5 deletions packages/server/src/adapters/standard/handler.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { AnyORPCError } from '@orpc/client'
import { ORPCError, toORPCError } from '@orpc/client'
import type { ErrorMap, Schema } from '@orpc/contract'
import { reconcileORPCError } from '@orpc/contract'
Expand Down Expand Up @@ -68,6 +69,11 @@ export interface StandardHandlerRoutingInterceptorOptions<
T extends Context,
> extends ResolvedStandardHandlerHandleOptions<T> {
request: StandardLazyRequest

/**
* Encodes an error the way procedure errors are encoded, to refuse a request with it.
*/
encodeError: (error: AnyORPCError) => Promisable<StandardResponse>
}
export type StandardHandlerRoutingInterceptor<T extends Context> = Interceptor<
StandardHandlerRoutingInterceptorOptions<T>,
Expand Down Expand Up @@ -120,6 +126,10 @@ export class StandardHandler<T extends Context> {
this.clientInterceptors = options.clientInterceptors
}

encodeError(error: AnyORPCError): Promisable<StandardResponse> {
return this.codec.encodeError(error)
}

async handle(
request: StandardLazyRequest,
options: StandardHandlerHandleOptions<T>,
Expand All @@ -134,7 +144,7 @@ export class StandardHandler<T extends Context> {

return intercept(
this.routingInterceptors,
{ context, prefix, request },
{ context, prefix, request, encodeError: (error) => this.encodeError(error) },
async ({ context, prefix, request }) => {
const span = getTracer()?.getActiveSpan()

Expand Down Expand Up @@ -242,10 +252,7 @@ export class StandardHandler<T extends Context> {
? error
: await reconcileORPCError(procedure['~orpc'].errorMap, error)

const response = await this.codec.encodeError(reconciled, procedure, path, {
context,
prefix,
})
const response = await this.codec.encodeError(reconciled)

return { matched: true, response }
}
Expand Down
34 changes: 6 additions & 28 deletions packages/server/src/adapters/standard/rpc-handler-codec.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ describe('rpcHandlerCodec', () => {
const codec = new RPCHandlerCodec(router, { serializer })
const error = new ORPCError('BAD_GATEWAY')

const response = codec.encodeError(error, procedure as any, ['ping'], options as any)
const response = codec.encodeError(error)

expect(response).toEqual({
headers: {},
Expand All @@ -222,9 +222,7 @@ describe('rpcHandlerCodec', () => {
const codec = new RPCHandlerCodec(router, { serializer })
const error = new ORPCError('toString' as any)

expect(
(await codec.encodeError(error, procedure as any, ['ping'], options as any)).status,
).toEqual(DEFAULT_ERROR_STATUS)
expect((await codec.encodeError(error)).status).toEqual(DEFAULT_ERROR_STATUS)
})

it('custom status with errorStatusCodes option', () => {
Expand All @@ -242,12 +240,7 @@ describe('rpcHandlerCodec', () => {
})

const overriddenError = new ORPCError('BAD_GATEWAY')
const overriddenResponse = codec.encodeError(
overriddenError,
procedure as any,
['ping'],
options as any,
)
const overriddenResponse = codec.encodeError(overriddenError)

expect(overriddenResponse).toEqual({
headers: {},
Expand All @@ -256,12 +249,7 @@ describe('rpcHandlerCodec', () => {
})

const unknownError = new ORPCError('UNKNOWN_CODE' as any)
const fallbackResponse = codec.encodeError(
unknownError,
procedure as any,
['ping'],
options as any,
)
const fallbackResponse = codec.encodeError(unknownError)

expect(fallbackResponse).toEqual({
headers: {},
Expand All @@ -288,12 +276,7 @@ describe('rpcHandlerCodec', () => {
})

const customizedError = new ORPCError('BAD_GATEWAY')
const customizedResponse = codec.encodeError(
customizedError,
procedure as any,
['ping'],
options as any,
)
const customizedResponse = codec.encodeError(customizedError)

expect(customizedResponse).toEqual({
headers: {},
Expand All @@ -302,12 +285,7 @@ describe('rpcHandlerCodec', () => {
})

const fallbackError = new ORPCError('UNKNOWN_ERROR')
const fallbackResponse = codec.encodeError(
fallbackError,
procedure as any,
['ping'],
options as any,
)
const fallbackResponse = codec.encodeError(fallbackError)

expect(fallbackResponse).toEqual({
headers: {},
Expand Down
7 changes: 1 addition & 6 deletions packages/server/src/adapters/standard/rpc-handler-codec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,12 +104,7 @@ export class RPCHandlerCodec<T extends Context> implements StandardHandlerCodec<
}
}

encodeError(
error: AnyORPCError,
_procedure: AnyProcedure,
_path: string[],
_options: ResolvedStandardHandlerHandleOptions<T>,
): Promisable<StandardResponse> {
encodeError(error: AnyORPCError): Promisable<StandardResponse> {
const status = getOwn(this.errorStatusMap, error.code) ?? DEFAULT_ERROR_STATUS

return {
Expand Down
5 changes: 5 additions & 0 deletions packages/server/src/adapters/standard/utils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { ORPCError } from '@orpc/client'
import type { Promisable, Value } from '@orpc/shared'
import type { StandardLazyRequest } from '@standard-server/core'

Expand All @@ -20,3 +21,7 @@ export function resolveFriendlyStandardHandlerHandleOptions<T extends Context>(
context: options.context ?? ({} as T), // Context only optional if all fields are optional
}
}

export function createNoProcedureMatchedError(): ORPCError<'NOT_FOUND', undefined> {
return new ORPCError('NOT_FOUND', { message: 'No procedure matched' })
}
Loading
Loading