koel/resources/assets/js/composables/useErrorHandler.ts

55 lines
1.4 KiB
TypeScript
Raw Normal View History

import axios, { AxiosResponse } from 'axios'
import { logger, parseValidationError } from '@/utils'
2024-04-23 21:01:27 +00:00
import { useDialogBox, useMessageToaster } from '@/composables'
export interface StatusMessageMap {
[key: AxiosResponse['status']]: string | Closure
}
type ErrorMessageDriver = 'toast' | 'dialog'
export const useErrorHandler = (driver: ErrorMessageDriver = 'toast') => {
const { toastError } = useMessageToaster()
const { showErrorDialog } = useDialogBox()
2024-04-23 21:01:27 +00:00
const showError = (message: string) => {
if (driver === 'toast') {
2024-04-23 21:01:27 +00:00
toastError(message)
} else {
2024-04-23 21:01:27 +00:00
showErrorDialog(message)
}
}
2024-04-23 21:01:27 +00:00
const showGenericError = () => showError('An unknown error occurred.')
const handleHttpError = (error: unknown, statusMessageMap: StatusMessageMap = {}) => {
logger.error(error)
if (!axios.isAxiosError(error)) {
return showGenericError()
}
2024-04-23 21:01:27 +00:00
if (!error.response?.status || !Object.prototype.hasOwnProperty.call(statusMessageMap, error.response.status)) {
showError('An unknown error occurred.')
return
}
if (error.response.status === 422) {
return showError(parseValidationError(error.response.data)[0])
}
const messageOrClosure = statusMessageMap[error.response.status]
if (typeof messageOrClosure === 'string') {
showError(messageOrClosure)
} else {
return messageOrClosure()
}
}
return {
handleHttpError,
showGenericError
}
}