2024-04-23 11:24:29 +00:00
|
|
|
import axios, { AxiosResponse } from 'axios'
|
|
|
|
import { logger, parseValidationError } from '@/utils'
|
2024-04-23 21:01:27 +00:00
|
|
|
import { useDialogBox, useMessageToaster } from '@/composables'
|
2024-04-23 11:24:29 +00:00
|
|
|
|
|
|
|
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) => {
|
2024-04-23 11:24:29 +00:00
|
|
|
if (driver === 'toast') {
|
2024-04-23 21:01:27 +00:00
|
|
|
toastError(message)
|
2024-04-23 11:24:29 +00:00
|
|
|
} else {
|
2024-04-23 21:01:27 +00:00
|
|
|
showErrorDialog(message)
|
2024-04-23 11:24:29 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-04-23 21:01:27 +00:00
|
|
|
const showGenericError = () => showError('An unknown error occurred.')
|
|
|
|
|
2024-04-23 11:40:50 +00:00
|
|
|
const handleHttpError = (error: unknown, statusMessageMap: StatusMessageMap = {}) => {
|
2024-04-23 11:24:29 +00:00
|
|
|
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)) {
|
2024-04-23 11:24:29 +00:00
|
|
|
showError('An unknown error occurred.')
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-04-23 11:40:50 +00:00
|
|
|
if (error.response.status === 422) {
|
2024-04-23 11:24:29 +00:00
|
|
|
return showError(parseValidationError(error.response.data)[0])
|
|
|
|
}
|
|
|
|
|
2024-04-23 11:40:50 +00:00
|
|
|
const messageOrClosure = statusMessageMap[error.response.status]
|
|
|
|
|
|
|
|
if (typeof messageOrClosure === 'string') {
|
|
|
|
showError(messageOrClosure)
|
2024-04-23 11:24:29 +00:00
|
|
|
} else {
|
2024-04-23 11:40:50 +00:00
|
|
|
return messageOrClosure()
|
2024-04-23 11:24:29 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
handleHttpError,
|
|
|
|
showGenericError
|
|
|
|
}
|
|
|
|
}
|