File size: 8,441 Bytes
9580dce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
import { describe, it, expect, vi } from "vitest";
import { NextRequest, NextResponse } from "next/server";
import { ApiError, withApiError } from "../api-error";

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

function makeRequest(path = "/api/test"): NextRequest {
  return new NextRequest(`http://localhost${path}`);
}

async function parseJson(response: NextResponse): Promise<unknown> {
  return response.json();
}

// ---------------------------------------------------------------------------
// ApiError class
// ---------------------------------------------------------------------------

describe("ApiError", () => {
  it("is an instance of Error", () => {
    const err = new ApiError(400, "Bad request");
    expect(err).toBeInstanceOf(Error);
  });

  it("stores statusCode and message", () => {
    const err = new ApiError(404, "Not found");
    expect(err.statusCode).toBe(404);
    expect(err.message).toBe("Not found");
  });

  it("sets name to 'ApiError'", () => {
    const err = new ApiError(500, "Server error");
    expect(err.name).toBe("ApiError");
  });

  it("has a stack trace", () => {
    const err = new ApiError(422, "Validation failed");
    expect(err.stack).toBeDefined();
    expect(err.stack).toContain("ApiError");
  });

  it("statusCode is readonly", () => {
    const err = new ApiError(403, "Forbidden");
    // TypeScript enforces readonly at compile time; at runtime we verify the value persists
    expect(err.statusCode).toBe(403);
  });
});

// ---------------------------------------------------------------------------
// withApiError β€” successful handler passthrough
// ---------------------------------------------------------------------------

describe("withApiError β€” success", () => {
  it("returns the handler's response when no error is thrown", async () => {
    const handler = vi.fn(async () =>
      NextResponse.json({ ok: true }, { status: 200 })
    );

    const wrapped = withApiError(handler);
    const req = makeRequest();
    const res = await wrapped(req);

    expect(handler).toHaveBeenCalledOnce();
    expect(res.status).toBe(200);
    expect(await parseJson(res)).toEqual({ ok: true });
  });

  it("passes request and context through to the handler", async () => {
    const handler = vi.fn(async () => NextResponse.json({}));
    const ctx = { params: { id: "42" } };

    const wrapped = withApiError(handler);
    await wrapped(makeRequest(), ctx);

    expect(handler).toHaveBeenCalledWith(expect.any(NextRequest), ctx);
  });

  it("works with synchronous handlers (returning NextResponse, not Promise)", async () => {
    const handler = vi.fn(() => NextResponse.json({ sync: true }));

    const wrapped = withApiError(handler);
    const res = await wrapped(makeRequest());

    expect(res.status).toBe(200);
    expect(await parseJson(res)).toEqual({ sync: true });
  });
});

// ---------------------------------------------------------------------------
// withApiError β€” ApiError handling
// ---------------------------------------------------------------------------

describe("withApiError β€” ApiError", () => {
  it("returns the correct status code for a 400 ApiError", async () => {
    const handler = async () => {
      throw new ApiError(400, "Missing field");
    };

    const wrapped = withApiError(handler);
    const res = await wrapped(makeRequest("/api/foo"));

    expect(res.status).toBe(400);
    const body = (await parseJson(res)) as { error: string; status: number };
    expect(body.error).toBe("Missing field");
    expect(body.status).toBe(400);
  });

  it("returns the correct status code for a 404 ApiError", async () => {
    const handler = async () => {
      throw new ApiError(404, "Not found");
    };

    const wrapped = withApiError(handler);
    const res = await wrapped(makeRequest());

    expect(res.status).toBe(404);
    const body = (await parseJson(res)) as { error: string; status: number };
    expect(body.error).toBe("Not found");
    expect(body.status).toBe(404);
  });

  it("returns the correct status code for a 422 ApiError", async () => {
    const handler = async () => {
      throw new ApiError(422, "Validation failed");
    };

    const wrapped = withApiError(handler);
    const res = await wrapped(makeRequest());

    expect(res.status).toBe(422);
  });

  it("logs to console.error with status code and path", async () => {
    const spy = vi.spyOn(console, "error").mockImplementation(() => {});

    const handler = async () => {
      throw new ApiError(403, "Forbidden");
    };

    const wrapped = withApiError(handler);
    await wrapped(makeRequest("/api/secret"));

    expect(spy).toHaveBeenCalledOnce();
    expect(spy.mock.calls[0][0]).toContain("[API 403]");
    expect(spy.mock.calls[0][0]).toContain("/api/secret");
    expect(spy.mock.calls[0][0]).toContain("Forbidden");

    spy.mockRestore();
  });
});

// ---------------------------------------------------------------------------
// withApiError β€” generic Error handling
// ---------------------------------------------------------------------------

describe("withApiError β€” generic Error", () => {
  it("returns 500 for a generic Error", async () => {
    const handler = async () => {
      throw new Error("Something broke");
    };

    const wrapped = withApiError(handler);
    const res = await wrapped(makeRequest());

    expect(res.status).toBe(500);
    const body = (await parseJson(res)) as { error: string; status: number };
    expect(body.error).toBe("Internal server error");
    expect(body.status).toBe(500);
  });

  it("does not leak the actual error message in the response body", async () => {
    const handler = async () => {
      throw new Error("Database password is hunter2");
    };

    const wrapped = withApiError(handler);
    const res = await wrapped(makeRequest());

    const body = (await parseJson(res)) as { error: string };
    expect(body.error).toBe("Internal server error");
    expect(body.error).not.toContain("hunter2");
  });

  it("logs the error message and stack to console.error", async () => {
    const spy = vi.spyOn(console, "error").mockImplementation(() => {});

    const handler = async () => {
      throw new Error("Detailed failure reason");
    };

    const wrapped = withApiError(handler);
    await wrapped(makeRequest("/api/broken"));

    expect(spy).toHaveBeenCalledOnce();
    expect(spy.mock.calls[0][0]).toContain("[API 500]");
    expect(spy.mock.calls[0][0]).toContain("/api/broken");
    expect(spy.mock.calls[0][0]).toContain("Detailed failure reason");
    // Second argument is the stack trace
    expect(spy.mock.calls[0][1]).toContain("Error");

    spy.mockRestore();
  });
});

// ---------------------------------------------------------------------------
// withApiError β€” non-Error throws
// ---------------------------------------------------------------------------

describe("withApiError β€” non-Error throws", () => {
  it("handles a thrown string", async () => {
    const handler = async () => {
      throw "string error";
    };

    const wrapped = withApiError(handler);
    const res = await wrapped(makeRequest());

    expect(res.status).toBe(500);
    const body = (await parseJson(res)) as { error: string };
    expect(body.error).toBe("Internal server error");
  });

  it("handles a thrown number", async () => {
    const handler = async () => {
      throw 42;
    };

    const wrapped = withApiError(handler);
    const res = await wrapped(makeRequest());

    expect(res.status).toBe(500);
  });

  it("handles a thrown null", async () => {
    const handler = async () => {
      throw null;
    };

    const wrapped = withApiError(handler);
    const res = await wrapped(makeRequest());

    expect(res.status).toBe(500);
  });

  it("logs the stringified value for non-Error throws", async () => {
    const spy = vi.spyOn(console, "error").mockImplementation(() => {});

    const handler = async () => {
      throw "oops";
    };

    const wrapped = withApiError(handler);
    await wrapped(makeRequest("/api/thing"));

    expect(spy).toHaveBeenCalledOnce();
    expect(spy.mock.calls[0][0]).toContain("oops");
    // No stack for non-Error β€” second arg should be empty string
    expect(spy.mock.calls[0][1]).toBe("");

    spy.mockRestore();
  });
});