Files
outline/server/routes/api/middlewares/apiErrorHandler.test.ts
T
Tom Moor 654c9c3b1e fix: Keep HTTP errors with "not found" in their message from becoming 404 (#14816)
* fix: Keep HTTP errors with "not found" in their message from becoming 404

* test: Expect 400 for an anchorNodeId that is not in the document
2026-11-30 18:24:56 -05:00

59 lines
1.8 KiB
TypeScript

import httpErrors from "http-errors";
import { AuthenticationError, ValidationError } from "@server/errors";
import apiErrorHandler from "./apiErrorHandler";
import type { AppContext } from "@server/types";
const createContext = (challenge?: string) => {
const headers: Record<string, string> = {};
if (challenge) {
headers["www-authenticate"] = challenge;
}
return {
response: {
get: (field: string) => headers[field.toLowerCase()] ?? "",
},
} as unknown as AppContext;
};
const runWithError = async (
ctx: AppContext,
error: Error = AuthenticationError()
) => {
try {
await apiErrorHandler()(ctx, () => Promise.reject(error));
} catch (err) {
if (httpErrors.isHttpError(err)) {
return err;
}
}
throw new Error("Expected an error");
};
describe("apiErrorHandler", () => {
it("should add a Bearer challenge to 401 errors", async () => {
const err = await runWithError(createContext());
expect(err.headers?.["WWW-Authenticate"]).toEqual("Bearer");
});
it("should keep a challenge already set on the response", async () => {
const err = await runWithError(createContext('Basic realm="custom"'));
expect(err.headers?.["WWW-Authenticate"]).toBeUndefined();
});
it("should keep an HTTP error whose message contains not found", async () => {
const err = await runWithError(
createContext(),
ValidationError("The specified text was not found in the document")
);
expect(err.status).toEqual(400);
expect(err.message).toEqual(
"The specified text was not found in the document"
);
});
it("should change a plain not found error to a 404", async () => {
const err = await runWithError(createContext(), new Error("Not found"));
expect(err.status).toEqual(404);
});
});