2022-12-11 21:44:52 +00:00
|
|
|
import type { H3Error } from 'h3'
|
2023-12-14 12:41:40 +00:00
|
|
|
import { createError as createH3Error } from 'h3'
|
2022-08-08 14:33:31 +00:00
|
|
|
import { toRef } from 'vue'
|
2022-09-14 09:22:03 +00:00
|
|
|
import { useNuxtApp } from '../nuxt'
|
2023-03-14 13:08:43 +00:00
|
|
|
import { useRouter } from './router'
|
2022-03-11 08:22:16 +00:00
|
|
|
|
2023-12-14 12:41:40 +00:00
|
|
|
export const NUXT_ERROR_SIGNATURE = '__nuxt_error'
|
|
|
|
|
2022-08-08 14:33:31 +00:00
|
|
|
export const useError = () => toRef(useNuxtApp().payload, 'error')
|
2022-03-11 08:22:16 +00:00
|
|
|
|
2023-12-14 12:41:40 +00:00
|
|
|
export interface NuxtError<DataT = unknown> extends H3Error<DataT> {}
|
2022-07-21 14:29:03 +00:00
|
|
|
|
2023-12-14 12:41:40 +00:00
|
|
|
export const showError = <DataT = unknown>(
|
|
|
|
error: string | Error | Partial<NuxtError<DataT>>
|
|
|
|
) => {
|
|
|
|
const nuxtError = createError<DataT>(error)
|
2022-07-21 14:29:03 +00:00
|
|
|
|
|
|
|
try {
|
|
|
|
const nuxtApp = useNuxtApp()
|
2022-08-08 14:33:31 +00:00
|
|
|
const error = useError()
|
2023-12-14 12:41:40 +00:00
|
|
|
|
2023-08-07 22:03:40 +00:00
|
|
|
if (import.meta.client) {
|
2023-12-14 12:41:40 +00:00
|
|
|
nuxtApp.hooks.callHook('app:error', nuxtError)
|
2023-05-01 22:55:24 +00:00
|
|
|
}
|
2023-12-14 12:41:40 +00:00
|
|
|
|
|
|
|
error.value = error.value || nuxtError
|
2022-07-21 14:29:03 +00:00
|
|
|
} catch {
|
2023-12-14 12:41:40 +00:00
|
|
|
throw nuxtError
|
2022-03-11 08:22:16 +00:00
|
|
|
}
|
|
|
|
|
2023-12-14 12:41:40 +00:00
|
|
|
return nuxtError
|
2022-03-11 08:22:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export const clearError = async (options: { redirect?: string } = {}) => {
|
|
|
|
const nuxtApp = useNuxtApp()
|
|
|
|
const error = useError()
|
2023-12-14 12:41:40 +00:00
|
|
|
|
2022-03-11 08:22:16 +00:00
|
|
|
nuxtApp.callHook('app:error:cleared', options)
|
2023-12-14 12:41:40 +00:00
|
|
|
|
2022-03-11 08:22:16 +00:00
|
|
|
if (options.redirect) {
|
2023-03-14 13:08:43 +00:00
|
|
|
await useRouter().replace(options.redirect)
|
2022-03-11 08:22:16 +00:00
|
|
|
}
|
2023-12-14 12:41:40 +00:00
|
|
|
|
2022-03-11 08:22:16 +00:00
|
|
|
error.value = null
|
|
|
|
}
|
2022-07-21 14:29:03 +00:00
|
|
|
|
2023-12-14 12:41:40 +00:00
|
|
|
export const isNuxtError = <DataT = unknown>(
|
|
|
|
error?: string | object
|
|
|
|
): error is NuxtError<DataT> => (
|
|
|
|
!!error && typeof error === 'object' && NUXT_ERROR_SIGNATURE in error
|
|
|
|
)
|
|
|
|
|
|
|
|
export const createError = <DataT = unknown>(
|
|
|
|
error: string | Partial<NuxtError<DataT>>
|
|
|
|
) => {
|
|
|
|
const nuxtError: NuxtError<DataT> = createH3Error<DataT>(error)
|
|
|
|
|
|
|
|
Object.defineProperty(nuxtError, NUXT_ERROR_SIGNATURE, {
|
|
|
|
value: true,
|
|
|
|
configurable: false,
|
|
|
|
writable: false
|
|
|
|
})
|
2022-07-21 14:29:03 +00:00
|
|
|
|
2023-12-14 12:41:40 +00:00
|
|
|
return nuxtError
|
2022-07-21 14:29:03 +00:00
|
|
|
}
|