Skip to content

Commit 2f9063b

Browse files
committed
test: add tests for error-handler
1 parent 18bcb8a commit 2f9063b

File tree

3 files changed

+59
-0
lines changed

3 files changed

+59
-0
lines changed

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,7 @@
114114
"@vue/test-utils": "2.4.6",
115115
"axe-core": "4.11.1",
116116
"fast-check": "4.5.3",
117+
"h3": "1.15.5",
117118
"knip": "5.83.0",
118119
"lint-staged": "16.2.7",
119120
"oxfmt": "0.27.0",

pnpm-lock.yaml

Lines changed: 3 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import { describe, expect, it } from 'vitest'
2+
import { createError } from 'h3'
3+
import * as v from 'valibot'
4+
import { handleApiError } from '../../../../server/utils/error-handler'
5+
6+
function h3Error(statusCode: number, message: string) {
7+
const error = createError({ statusCode, message })
8+
error.statusCode = statusCode
9+
return error
10+
}
11+
12+
describe('handleApiError', () => {
13+
const fallback = { message: 'Something went wrong', statusCode: 500 }
14+
15+
it('re-throws H3 errors as-is', () => {
16+
const h3Err = createError({ statusCode: 404, message: 'Not found' })
17+
18+
expect(() => handleApiError(h3Err, fallback)).toThrow(h3Err)
19+
})
20+
21+
it('throws a 404 with the first issue message for valibot errors', () => {
22+
const schema = v.object({ name: v.pipe(v.string(), v.minLength(1, 'Name is required')) })
23+
24+
let valibotError: unknown
25+
try {
26+
v.parse(schema, { name: '' })
27+
} catch (e) {
28+
valibotError = e
29+
}
30+
31+
const expected = h3Error(404, 'Name is required')
32+
expect(() => handleApiError(valibotError, fallback)).toThrow(expected)
33+
})
34+
35+
it('throws a fallback error with the given statusCode and message', () => {
36+
const expected = h3Error(502, 'Bad gateway')
37+
expect(() =>
38+
handleApiError(new Error('unexpected'), { message: 'Bad gateway', statusCode: 502 }),
39+
).toThrow(expected)
40+
})
41+
42+
it('defaults fallback statusCode to 502 when not provided', () => {
43+
const expected = h3Error(502, 'Upstream failed')
44+
expect(() => handleApiError('some string error', { message: 'Upstream failed' })).toThrow(
45+
expected,
46+
)
47+
})
48+
49+
it('uses the custom fallback statusCode when provided', () => {
50+
const expected = h3Error(503, 'Service unavailable')
51+
expect(() => handleApiError(null, { message: 'Service unavailable', statusCode: 503 })).toThrow(
52+
expected,
53+
)
54+
})
55+
})

0 commit comments

Comments
 (0)