errors.test.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /* @vitest-environment node */
  2. import { describe, it, expect } from "vitest";
  3. import { jsonError, withErrorHandling, badRequest } from "./errors.js";
  4. describe("lib/api/errors", () => {
  5. it("jsonError returns the standardized error shape without details", async () => {
  6. const res = jsonError(401, "AUTH_UNAUTHENTICATED", "Unauthorized");
  7. expect(res.status).toBe(401);
  8. expect(await res.json()).toEqual({
  9. error: { message: "Unauthorized", code: "AUTH_UNAUTHENTICATED" },
  10. });
  11. });
  12. it("jsonError includes details when provided", async () => {
  13. const res = jsonError(
  14. 400,
  15. "VALIDATION_MISSING_PARAM",
  16. "Missing required route parameter(s)",
  17. { params: ["branch"] }
  18. );
  19. expect(res.status).toBe(400);
  20. expect(await res.json()).toEqual({
  21. error: {
  22. message: "Missing required route parameter(s)",
  23. code: "VALIDATION_MISSING_PARAM",
  24. details: { params: ["branch"] },
  25. },
  26. });
  27. });
  28. it("withErrorHandling converts ApiError into a standardized response", async () => {
  29. // The wrapped handler throws an expected error (ApiError).
  30. // The wrapper must convert it into { error: { message, code } } with status 400.
  31. const handler = withErrorHandling(async () => {
  32. throw badRequest("VALIDATION_TEST", "Bad Request");
  33. });
  34. const res = await handler();
  35. expect(res.status).toBe(400);
  36. expect(await res.json()).toEqual({
  37. error: { message: "Bad Request", code: "VALIDATION_TEST" },
  38. });
  39. });
  40. it("withErrorHandling converts unknown errors into a safe 500 response", async () => {
  41. // Unknown errors must never leak internal messages/stacks.
  42. // We always return a generic 500 payload.
  43. const handler = withErrorHandling(async () => {
  44. throw new Error("boom");
  45. });
  46. const res = await handler();
  47. expect(res.status).toBe(500);
  48. expect(await res.json()).toEqual({
  49. error: {
  50. message: "Internal server error",
  51. code: "INTERNAL_SERVER_ERROR",
  52. },
  53. });
  54. });
  55. });