Skip to content

Commit 8e6df61

Browse files
committed
Validate method existence and standardize error handling
1 parent eee4a4d commit 8e6df61

File tree

2 files changed

+17
-3
lines changed

2 files changed

+17
-3
lines changed

src/router.test.ts

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,14 @@ describe("router", () => {
8484
expect((error as JSONRPCErrorObject).code).toBe(-32601);
8585
});
8686

87+
it("returns not found error when method is not implemented", async () => {
88+
const methodMapping = makeMethodMapping(parsedExample.methods as MethodObject[]);
89+
delete methodMapping["addition"];
90+
const router = new Router(parsedExample, methodMapping);
91+
const { error } = await router.call("addition", [2, 2]);
92+
expect((error as JSONRPCErrorObject).code).toBe(-32601);
93+
});
94+
8795
it("returns param validation error when passing incorrect params", async () => {
8896
const router = new Router(parsedExample, makeMethodMapping(parsedExample.methods as MethodObject[]));
8997
const { error } = await router.call("addition", ["123", "321"]);
@@ -101,8 +109,9 @@ describe("router", () => {
101109
it("returns Unknown Error data when thrown", async () => {
102110
const router = new Router(parsedExample, makeMethodMapping(parsedExample.methods as MethodObject[]));
103111
const { error } = await router.call("unknown-error", []);
104-
expect((error as JSONRPCErrorObject).code).toBe(6969);
105-
expect((error as JSONRPCErrorObject).message).toBe("unknown error");
112+
expect((error as JSONRPCErrorObject).code).toBe(-32603);
113+
expect((error as JSONRPCErrorObject).message).toBe("Internal error");
114+
expect((error as JSONRPCErrorObject).data).toBe("unanticpated crash");
106115
});
107116

108117
it("implements service discovery", async () => {

src/router.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,10 @@ export class Router {
7979
return this.invalidParamsHandler(validationErrors);
8080
}
8181

82+
if (!this.isMethodImplemented(methodName)) {
83+
return Router.methodNotFoundHandler(methodName);
84+
}
85+
8286
const methodObject = (this.openrpcDocument.methods as MethodObject[]).find((m) => m.name === methodName) as MethodObject;
8387

8488
const paramsAsArray = params instanceof Array ? params : toArray(methodObject, params);
@@ -89,7 +93,8 @@ export class Router {
8993
if (e instanceof JSONRPCError) {
9094
return { error: { code: e.code, message: e.message, data: e.data } };
9195
}
92-
return { error: { code: 6969, message: "unknown error" } };
96+
const message = e instanceof Error ? e.message : String(e);
97+
return { error: { code: -32603, message: "Internal error", data: message } };
9398
}
9499
}
95100

0 commit comments

Comments
 (0)