|
| 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 | +describe('handleApiError', () => { |
| 7 | + const fallback = { message: 'Something went wrong', statusCode: 500 } |
| 8 | + |
| 9 | + it('re-throws H3 errors as-is', () => { |
| 10 | + const h3Err = createError({ statusCode: 404, message: 'Not found' }) |
| 11 | + |
| 12 | + expect(() => handleApiError(h3Err, fallback)).toThrow(h3Err) |
| 13 | + }) |
| 14 | + |
| 15 | + it('throws a 404 with the first issue message for valibot errors', () => { |
| 16 | + const schema = v.object({ name: v.pipe(v.string(), v.minLength(1, 'Name is required')) }) |
| 17 | + |
| 18 | + let valibotError: unknown |
| 19 | + try { |
| 20 | + v.parse(schema, { name: '' }) |
| 21 | + } catch (e) { |
| 22 | + valibotError = e |
| 23 | + } |
| 24 | + |
| 25 | + expect(() => handleApiError(valibotError, fallback)).toThrow( |
| 26 | + expect.objectContaining({ statusCode: 404, message: 'Name is required' }), |
| 27 | + ) |
| 28 | + }) |
| 29 | + |
| 30 | + it('throws a fallback error with the given statusCode and message', () => { |
| 31 | + expect(() => |
| 32 | + handleApiError(new Error('unexpected'), { message: 'Bad gateway', statusCode: 502 }), |
| 33 | + ).toThrow(expect.objectContaining({ statusCode: 502, message: 'Bad gateway' })) |
| 34 | + }) |
| 35 | + |
| 36 | + it('defaults fallback statusCode to 502 when not provided', () => { |
| 37 | + expect(() => handleApiError('some string error', { message: 'Upstream failed' })).toThrow( |
| 38 | + expect.objectContaining({ statusCode: 502, message: 'Upstream failed' }), |
| 39 | + ) |
| 40 | + }) |
| 41 | + |
| 42 | + it('uses the custom fallback statusCode when provided', () => { |
| 43 | + expect(() => handleApiError(null, { message: 'Service unavailable', statusCode: 503 })).toThrow( |
| 44 | + expect.objectContaining({ statusCode: 503, message: 'Service unavailable' }), |
| 45 | + ) |
| 46 | + }) |
| 47 | +}) |
0 commit comments