Tutorials
How to Catch Error Serialization Failures in oRPC 1.17.3
oRPC 1.17.3 changes what happens when the server fails to serialize an error. Instead of attempting another encoding operation, the handler propagates the exception to the surrounding application.
A procedure throws an error. The server catches it, prepares an HTTP response, and sends the error information to the client.
At least, that is what should happen.
But what if the error itself contains data that the server cannot serialize? Perhaps an object contains a circular reference, a property getter throws an exception, or a custom serializer fails while processing its value.
The procedure has already failed, and now the mechanism responsible for reporting that failure encounters another exception.
Until recently, oRPC attempted to recover from this situation by encoding a replacement INTERNAL_SERVER_ERROR.
On December 1, 2026, oRPC released version 1.17.3, changing that behavior. If the server’s encodeError() method throws, the exception now propagates to the surrounding application instead of triggering another encoding attempt.
For applications with centralized error handling, this changes where certain failures become visible.
A procedure error and an encoding error are different things
Consider a simple oRPC procedure:
import { os, ORPCError } from "@orpc/server";
export const getUser = os.handler(() => {
throw new ORPCError("NOT_FOUND", {
message: "User not found",
data: {
userId: "42",
},
});
});
The procedure throws an intentional application error.
oRPC converts the exception into an error response containing its code, status, message, and additional data.
The client receives a structured representation of the failure.
But the ORPCError instance cannot be transmitted directly. Its contents must first pass through the response codec.
For the RPC protocol, the relevant operation is effectively:
serializer.serialize(error.toJSON());
There is no particular difficulty with the previous example. Its data contains only a string.
Now consider an object that references itself:
const data: Record<string, unknown> = {
userId: "42",
};
data.self = data;
throw new ORPCError("BAD_REQUEST", {
data,
});
The object is valid JavaScript. TypeScript has no reason to reject it.
However, oRPC’s RPC JSON serializer recursively processes object properties. Following self leads back to the same object, which can eventually cause a stack overflow.
The original BAD_REQUEST is no longer the only problem. Encoding its response has failed as well.
What changed in oRPC 1.17.3?
Before the update, the standard handler contained a recovery mechanism that can be represented as follows:
try {
response = codec.encodeError(error);
} catch (cause) {
response = codec.encodeError(
new ORPCError("INTERNAL_SERVER_ERROR", {
cause,
})
);
}
The handler attempted to encode a second error when the first encoding operation failed.
If the replacement succeeded, the HTTP adapter received a normal error response. The encoding exception could therefore remain invisible to an application’s outer exception handler, although the previous implementation did record it on a tracing span.
PR #2577 removes this fallback.
The relevant operation is now:
const response = this.codec.encodeError(error);
If it throws, the exception escapes the standard handler.
flowchart TD
A["Procedure throws an error"] --> B["Encode error response"]
B --> C{"Encoding succeeds?"}
C -->|Yes| D["Return RPC error response"]
C -->|No| E{"oRPC version"}
E -->|Previous behavior| F["Try encoding INTERNAL_SERVER_ERROR"]
E -->|1.17.3| G["Propagate encoding exception"]
G --> H["Application error handler"]
Ordinary procedure errors are still converted into RPC responses.
The change specifically concerns failures that occur while encoding an error response.
1. Update the server package
For an existing oRPC 1.x application:
pnpm add @orpc/[email protected]
Check the installed version:
pnpm list @orpc/server
If your application uses other oRPC packages, keep their versions compatible with the server package.
The following examples use the Fetch API adapter, which allows the error-handling behavior to be tested without starting an HTTP server.
2. Catch failures at the HTTP boundary
An ordinary oRPC Fetch adapter integration calls handler.handle() and returns the resulting response.
With the new behavior, that asynchronous operation may reject when error encoding fails.
The surrounding application can catch the exception:
// server.ts
import { RPCHandler } from "@orpc/server/fetch";
import { router } from "./router";
export const handler = new RPCHandler(router);
export async function handleRequest(
request: Request
): Promise<Response> {
try {
const { matched, response } = await handler.handle(
request,
{
prefix: "/rpc",
context: {},
}
);
return matched
? response
: new Response("Not Found", { status: 404 });
} catch (error: unknown) {
console.error("RPC handler failed:", error);
return Response.json(
{
json: {
defined: false,
code: "INTERNAL_SERVER_ERROR",
status: 500,
message: "Internal server error",
},
meta: [],
},
{
status: 500,
}
);
}
}
Notice that the fallback response is constructed independently of the oRPC codec.
There would be little benefit in passing the exception back into the same serialization mechanism that has just failed.
The response also follows oRPC’s RPC protocol structure. Returning an arbitrary JSON object such as { message: "Internal server error" } would produce a valid HTTP response, but not a properly structured oRPC error response.
The distinction matters when the receiving application uses RPCLink and expects an ORPCError.
This outer catch is not limited to serialization failures. It can also receive other exceptions escaping the adapter, so the log message deliberately describes a handler failure rather than assuming every exception originated in encodeError().
3. Where should serialization failures be logged?
oRPC already provides interceptors and middleware for observing errors.
However, their location in the execution lifecycle matters.
A procedure-level middleware can observe an exception thrown by the procedure. It cannot necessarily observe an exception that occurs later, after the procedure has returned control to the surrounding handler.
The same consideration applies to standard request interceptors. In the 1.17.3 implementation, error encoding occurs outside the inner interceptor execution.
An outer HTTP error handler, root interceptor, or adapter interceptor is therefore a more appropriate boundary for catching failures from encodeError().
That does not mean every application needs another logging mechanism.
If your HTTP framework already provides centralized exception handling, the propagated exception can be handled there.
The useful part of this update is that the application is no longer dependent on oRPC successfully encoding a replacement error before regaining control.
One limitation remains: the exception reaching the outer handler is the encoding failure itself. It does not necessarily contain the original procedure error. If both failures need to be recorded, they should be observed at their respective stages and correlated through a request identifier.
4. Write a regression test with Vitest
A circular reference is one possible way to trigger a serialization failure, but testing for a specific stack overflow message can make the test unnecessarily dependent on the JavaScript runtime.
Instead, create a property getter that throws a known exception when the serializer attempts to read it.
Install Vitest:
pnpm add -D vitest
Create a small test router:
// router.ts
import { os, ORPCError } from "@orpc/server";
export const encodingFailure = new Error(
"Unable to serialize error data"
);
export const router = {
normalError: os.handler(() => {
throw new ORPCError("BAD_REQUEST", {
data: {
reason: "Invalid input",
},
});
}),
brokenError: os.handler(() => {
throw new ORPCError("BAD_REQUEST", {
data: {
get details() {
throw encodingFailure;
},
},
});
}),
};
The first procedure throws an ordinary error containing serializable data.
The second also throws an ORPCError, but its details property fails when accessed during serialization.
These procedures are intended for an isolated test project, not a production router.
Now create server.test.ts:
import { describe, expect, it, vi } from "vitest";
import {
handler,
handleRequest,
} from "./server";
import { encodingFailure } from "./router";
function createRequest(procedure: string) {
return new Request(
`http://localhost/rpc/${procedure}`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
json: null,
}),
}
);
}
describe("oRPC error serialization", () => {
it("returns ordinary procedure errors", async () => {
const response = await handleRequest(
createRequest("normalError")
);
expect(response.status).toBe(400);
const body = await response.json();
expect(body.json.code).toBe("BAD_REQUEST");
});
it("propagates an encoding failure", async () => {
await expect(
handler.handle(createRequest("brokenError"), {
prefix: "/rpc",
context: {},
})
).rejects.toBe(encodingFailure);
});
it("returns a safe fallback response", async () => {
const logger = vi
.spyOn(console, "error")
.mockImplementation(() => {});
try {
const response = await handleRequest(
createRequest("brokenError")
);
expect(response.status).toBe(500);
const body = await response.json();
expect(body.json.code).toBe(
"INTERNAL_SERVER_ERROR"
);
expect(body.json.message).toBe(
"Internal server error"
);
expect(logger).toHaveBeenCalledWith(
"RPC handler failed:",
encodingFailure
);
} finally {
logger.mockRestore();
}
});
});
Run the tests:
pnpm exec vitest run
The three tests verify different parts of the error-handling lifecycle.
| Scenario | Expected behavior |
|---|---|
| Ordinary procedure error | Structured HTTP 400 response |
| Error encoding failure | Handler rejects with the encoding exception |
| Encoding failure caught by the application | Exception is logged and a safe HTTP 500 is returned |
The examples are based on the released implementation. The complete integration test has not been independently executed for this article.
The official regression test in PR #2577 verifies the underlying behavior directly: encodeError() is called once, and the handler rejects with the exact exception thrown by the codec.
5. Avoid passing internal objects as error data
A centralized exception handler protects the HTTP boundary, but it does not correct the original problem.
Consider an error containing an entire request object:
throw new ORPCError("BAD_REQUEST", {
data: {
request,
databaseConnection,
},
});
Even if these objects happen to serialize successfully, sending them to the client is rarely appropriate.
They may contain sensitive information, internal state, or references to other objects that were never designed for network transmission.
A smaller error payload is easier to control:
throw new ORPCError("BAD_REQUEST", {
message: "Invalid request",
data: {
field: "email",
reason: "INVALID_FORMAT",
},
});
Internal diagnostic information should remain on the server.
oRPC explicitly documents that ORPCError.data is transmitted to the client. A TypeScript type does not establish that a value is safe to expose or that every property can be serialized successfully.
Defining error payloads with .errors() and an appropriate validation schema can help keep their structure predictable.
It still makes sense to maintain a final exception boundary for failures that validation does not prevent.
Does this change affect existing applications?
Applications that already catch exceptions at the HTTP or framework level may require little or no modification.
The difference is more noticeable in applications that assume handler.handle() will always resolve to a matched or unmatched result.
That assumption is no longer valid for error encoding failures that previously benefited from the fallback.
There is also a boundary to what an HTTP-level catch can recover from. If a streamed response has already started reaching the client, replacing it with a new HTTP 500 may no longer be possible. Streaming errors require separate handling.
The December 1 patch does not attempt to make every error object serializable.
It changes what happens when serialization fails.
Instead of replacing the encoding exception with another error and attempting to encode it again, oRPC allows the surrounding application to decide how that failure should be recorded and reported.
For an application with centralized error handling, that distinction can determine whether a serialization defect becomes an actionable exception or merely another HTTP 500 in the access log.