60 lines
2.3 KiB
TypeScript
60 lines
2.3 KiB
TypeScript
import { describe, expect, test } from "vitest";
|
|
|
|
import { CatalogError, foundationErrors, toPinoLogObject } from "./errors.js";
|
|
|
|
describe("CatalogError", () => {
|
|
test("derives message from the definition message when present and copies metadata", () => {
|
|
const definition = { code: "x.broken", status: 418, i18nKey: "x.errors.broken", message: "I am a teapot" };
|
|
const error = new CatalogError(definition, { teapot: true });
|
|
|
|
expect(error).toBeInstanceOf(Error);
|
|
expect(error.name).toBe("CatalogError");
|
|
expect(error.message).toBe("I am a teapot");
|
|
expect(error.code).toBe("x.broken");
|
|
expect(error.status).toBe(418);
|
|
expect(error.i18nKey).toBe("x.errors.broken");
|
|
expect(error.details).toEqual({ teapot: true });
|
|
});
|
|
|
|
test("falls back to the code as message when no definition message is set", () => {
|
|
const error = new CatalogError(foundationErrors.notFound);
|
|
|
|
expect(error.message).toBe(foundationErrors.notFound.code);
|
|
expect(error.status).toBe(404);
|
|
expect(error.details).toBeUndefined();
|
|
});
|
|
});
|
|
|
|
describe("toPinoLogObject", () => {
|
|
test("serializes a CatalogError into a structured catalog shape", () => {
|
|
const error = new CatalogError(foundationErrors.forbidden, { permission: "thing.view" });
|
|
|
|
expect(toPinoLogObject(error)).toEqual({
|
|
error: {
|
|
name: "CatalogError",
|
|
message: foundationErrors.forbidden.code,
|
|
code: "foundation.forbidden",
|
|
status: 403,
|
|
i18nKey: "foundation.errors.forbidden",
|
|
details: { permission: "thing.view" },
|
|
},
|
|
});
|
|
});
|
|
|
|
test("serializes a plain Error with its stack but no catalog fields", () => {
|
|
const error = new Error("plain boom");
|
|
|
|
const logged = toPinoLogObject(error) as { error: { name: string; message: string; stack?: string; code?: string } };
|
|
expect(logged.error.name).toBe("Error");
|
|
expect(logged.error.message).toBe("plain boom");
|
|
expect(typeof logged.error.stack).toBe("string");
|
|
expect(logged.error.code).toBeUndefined();
|
|
});
|
|
|
|
test("wraps non-Error throwables verbatim", () => {
|
|
expect(toPinoLogObject("just a string")).toEqual({ error: "just a string" });
|
|
expect(toPinoLogObject({ weird: 1 })).toEqual({ error: { weird: 1 } });
|
|
expect(toPinoLogObject(undefined)).toEqual({ error: undefined });
|
|
});
|
|
});
|