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:12:55 +00:00
|
|
|
const showError = (message: string) => driver === 'toast' ? toastError(message) : 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)
|
|
|
|
|
2024-04-23 21:12:55 +00:00
|
|
|
if (!axios.isAxiosError(error) || !error.response?.status) {
|
2024-04-23 11:24:29 +00:00
|
|
|
return showGenericError()
|
|
|
|
}
|
|
|
|
|
2024-04-23 21:12:55 +00:00
|
|
|
if (
|
|
|
|
!Object.prototype.hasOwnProperty.call(statusMessageMap, error.response.status)
|
|
|
|
&& 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]
|
|
|
|
|
2024-05-19 05:49:42 +00:00
|
|
|
if (messageOrClosure) {
|
|
|
|
return typeof messageOrClosure === 'string' ? showError(messageOrClosure) : messageOrClosure()
|
|
|
|
}
|
|
|
|
|
|
|
|
if (error.response.data.message) {
|
|
|
|
return showError(error.response.data.message)
|
|
|
|
}
|
|
|
|
|
|
|
|
return showGenericError()
|
2024-04-23 11:24:29 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
handleHttpError,
|
|
|
|
showGenericError
|
|
|
|
}
|
|
|
|
}
|