|
| 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