forked from npmx-dev/npmx.dev
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherror-handler.ts
More file actions
30 lines (27 loc) · 776 Bytes
/
error-handler.ts
File metadata and controls
30 lines (27 loc) · 776 Bytes
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
import { isError, createError } from 'h3'
import * as v from 'valibot'
import type { ErrorOptions } from '#shared/types/error'
/**
* Generic error handler for Nitro routes
* Handles H3 errors, Valibot, and fallbacks in that order
* @public
*/
export function handleApiError(error: unknown, fallback: ErrorOptions): never {
// If already a known Nuxt/H3 Error, re-throw
if (isError(error)) {
throw error
}
// Handle Valibot validation errors
if (v.isValiError(error)) {
throw createError({
// TODO: throwing 404 rather than 400 as it's cacheable
statusCode: 404,
message: error.issues[0].message,
})
}
// Generic fallback
throw createError({
statusCode: fallback.statusCode ?? 502,
message: fallback.message,
})
}