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

43 lines
1.3 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:12:55 +00:00
const showError = (message: string) => driver === 'toast' ? toastError(message) : 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)
2024-04-23 21:12:55 +00:00
if (!axios.isAxiosError(error) || !error.response?.status) {
return showGenericError()
}
2024-04-23 21:12:55 +00:00
if (
!Object.prototype.hasOwnProperty.call(statusMessageMap, error.response.status)
&& error.response.status === 422
) {
return showError(parseValidationError(error.response.data)[0])
}
const messageOrClosure = statusMessageMap[error.response.status]
2024-04-23 21:12:55 +00:00
return typeof messageOrClosure === 'string' ? showError(messageOrClosure) : messageOrClosure()
}
return {
handleHttpError,
showGenericError
}
}