Skip to content

Commit c106dcf

Browse files
committed
test: custom error handler
1 parent e9b74e7 commit c106dcf

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

src/core/definer.test.ts

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,4 +244,69 @@ describe("defineRoute", () => {
244244

245245
console.log = originalLog;
246246
});
247+
248+
it("should use custom error handler correctly for an expected error", async () => {
249+
mockRequest.json.mockImplementation(() => {
250+
throw new SyntaxError("Unexpected end of JSON input");
251+
});
252+
253+
const route = defineRoute({
254+
operationId: "postExample",
255+
method: "POST",
256+
summary: "Post Example",
257+
description: "Posts example data",
258+
tags: ["example"],
259+
requestBody: z.object({ name: z.string() }),
260+
action: mockAction,
261+
responses: {
262+
200: { description: "OK" },
263+
418: { description: "I'm a teapot" },
264+
},
265+
handleErrors: (_errorType, _cause) => {
266+
return new Response("I'm a teapot", { status: 418 });
267+
},
268+
});
269+
270+
const nextJsRouteHandler = route.POST;
271+
272+
const response = await nextJsRouteHandler(mockRequest as unknown as Request, {});
273+
const bodyText = await response.text();
274+
275+
expect(response).toBeInstanceOf(Response);
276+
expect(response.status).toBe(418);
277+
expect(bodyText).toBe("I'm a teapot");
278+
});
279+
280+
it("should use custom error handler correctly for an unexpected error", async () => {
281+
const route = defineRoute({
282+
operationId: "getExample",
283+
method: "GET",
284+
summary: "Get Example",
285+
description: "Fetches example data",
286+
tags: ["example"],
287+
action: () => {
288+
throw new Error("Critical error");
289+
},
290+
responses: {
291+
200: { description: "OK" },
292+
418: { description: "I'm a teapot" },
293+
500: { description: "Backend developer is gonna get fired" },
294+
},
295+
handleErrors: (errorType, _cause) => {
296+
if (errorType === "UNKNOWN_ERROR") {
297+
return new Response("Backend developer is gonna get fired", { status: 500 });
298+
}
299+
return new Response(errorType, { status: 418 });
300+
},
301+
});
302+
303+
const nextJsRouteHandler = route.GET;
304+
305+
const response = await nextJsRouteHandler(mockRequest as unknown as Request, {});
306+
const bodyText = await response.text();
307+
308+
expect(response).toBeInstanceOf(Response);
309+
expect(response.status).toBe(500);
310+
expect(bodyText).toBe("Backend developer is gonna get fired");
311+
});
247312
});

0 commit comments

Comments
 (0)