import { BASE_URL } from "../helpers.ts"; import { assertEquals } from "@std/assert"; import { Application } from "@oak/oak"; import { errorMiddleware } from "../../middleware/error.ts"; import { APIErrorCode } from "../../../shared/api.ts"; import { APIException } from "../../lib/api-exception.ts"; async function handle( app: Application, path: string, headers: HeadersInit = {}, ) { const res = await app.handle(new Request(`${BASE_URL}${path}`, { headers })); if (!res) throw new Error("no response"); return { res, text: await res.text() }; } Deno.test("errorMiddleware: APIExceptions keep their status, anything else is a bare 500", async () => { const app = new Application(); app.use(errorMiddleware); app.use((ctx) => { if (ctx.request.url.pathname === "/api-error") { throw new APIException(APIErrorCode.NOT_FOUND, 404, "Nope"); } throw new Error("secret internals"); }); const known = await handle(app, "/api-error"); assertEquals(known.res.status, 404); assertEquals(JSON.parse(known.text), { success: false, error: { code: "NOT_FOUND", message: "Nope" }, }); const unknown = await handle(app, "/boom"); assertEquals(unknown.res.status, 500); assertEquals(JSON.parse(unknown.text).error, { code: "SERVER_ERROR", message: "Unexpected server error", }); });