Skip to content

Commit

Permalink
fix: don't wrap procedure-thrown errors
Browse files Browse the repository at this point in the history
  • Loading branch information
angeloashmore committed Mar 15, 2023
1 parent b70d57f commit bb5e242
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 11 deletions.
8 changes: 7 additions & 1 deletion src/client/createRPCClient.ts
Expand Up @@ -6,6 +6,7 @@ import { isErrorLike } from "../lib/isErrorLike";
import { Procedures, Procedure, ProcedureCallServerResponse } from "../types";
import { R19Error } from "../R19Error";
import { isPlainObject } from "../lib/isPlainObject";
import { isR19ErrorLike } from "../isR19ErrorLike";

const createArbitrarilyNestedFunction = <T>(
handler: (path: string[], args: unknown[]) => unknown,
Expand Down Expand Up @@ -149,11 +150,16 @@ export const createRPCClient = <TProcedures extends Procedures>(
if ("error" in resObject) {
const resError = resObject.error;

if (isErrorLike(resError)) {
if (isR19ErrorLike(resError)) {
const error = new R19Error(resError.message, {
procedurePath,
procedureArgs,
});
error.stack = resError.stack;

throw error;
} else if (isErrorLike(resError)) {
const error = new Error(resError.message);
error.name = resError.name;
error.stack = resError.stack;

Expand Down
17 changes: 11 additions & 6 deletions src/handleRPCRequest.ts
Expand Up @@ -11,6 +11,7 @@ import {
OnErrorEventHandler,
} from "./types";
import { R19Error } from "./R19Error";
import { isR19ErrorLike } from "./isR19ErrorLike";

const findProcedure = (
procedures: Procedures,
Expand Down Expand Up @@ -130,12 +131,16 @@ export const handleRPCRequest = async <TProcedures extends Procedures>(
if (isErrorLike(error)) {
const body = encode(
{
error: {
name: error.name,
message: error.message,
stack:
process.env.NODE_ENV === "development" ? error.stack : undefined,
},
error: isR19ErrorLike(error)
? error
: {
name: error.name,
message: error.message,
stack:
process.env.NODE_ENV === "development"
? error.stack
: undefined,
},
},
{ ignoreUndefined: true },
);
Expand Down
5 changes: 1 addition & 4 deletions src/isR19ErrorLike.ts
Expand Up @@ -7,9 +7,6 @@ export type R19ErrorLike = ErrorLike & {

export const isR19ErrorLike = (error: unknown): error is R19ErrorLike => {
return (
isErrorLike(error) &&
error.name === "R19Error" &&
"procedurePath" in error &&
"procedureArgs" in error
isErrorLike(error) && error.name === "R19Error" && "procedurePath" in error
);
};
10 changes: 10 additions & 0 deletions test/isR19ErrorLike.test.ts
Expand Up @@ -13,6 +13,16 @@ it("returns true if the input is shaped like an R19 error", () => {
).toBe(true);
});

it("supports optional procedureArgs", () => {
expect(
isR19ErrorLike({
name: "R19Error",
message: "message",
procedurePath: ["foo"],
}),
).toBe(true);
});

it("returns false if the input is not shaped like an R19 error", () => {
// Wrong name
expect(
Expand Down

0 comments on commit bb5e242

Please sign in to comment.