import { ApiStatus } from './status' import { $t } from '@/locales' class HttpError extends Error { constructor(message, code, options) { super(message) this.name = 'HttpError' this.code = code this.data = options?.data this.timestamp = /* @__PURE__ */ new Date().toISOString() this.url = options?.url this.method = options?.method } toLogData() { return { code: this.code, message: this.message, data: this.data, timestamp: this.timestamp, url: this.url, method: this.method, stack: this.stack } } } const getErrorMessage = (status) => { const errorMap = { [ApiStatus.unauthorized]: 'httpMsg.unauthorized', [ApiStatus.forbidden]: 'httpMsg.forbidden', [ApiStatus.notFound]: 'httpMsg.notFound', [ApiStatus.methodNotAllowed]: 'httpMsg.methodNotAllowed', [ApiStatus.requestTimeout]: 'httpMsg.requestTimeout', [ApiStatus.internalServerError]: 'httpMsg.internalServerError', [ApiStatus.badGateway]: 'httpMsg.badGateway', [ApiStatus.serviceUnavailable]: 'httpMsg.serviceUnavailable', [ApiStatus.gatewayTimeout]: 'httpMsg.gatewayTimeout' } return $t(errorMap[status] || 'httpMsg.internalServerError') } function handleError(error) { if (error.code === 'ERR_CANCELED') { console.warn('Request cancelled:', error.message) throw new HttpError($t('httpMsg.requestCancelled'), ApiStatus.error) } const statusCode = error.response?.status const errorMessage = error.response?.data?.msg || error.message const requestConfig = error.config if (!error.response) { throw new HttpError($t('httpMsg.networkError'), ApiStatus.error, { url: requestConfig?.url, method: requestConfig?.method?.toUpperCase() }) } const message = statusCode ? getErrorMessage(statusCode) : errorMessage || $t('httpMsg.requestFailed') throw new HttpError(message, statusCode || ApiStatus.error, { data: error.response.data, url: requestConfig?.url, method: requestConfig?.method?.toUpperCase() }) } function showError(error, showMessage = true) { if (showMessage) { ElMessage.error(error.message) } console.error('[HTTP Error]', error.toLogData()) } function showSuccess(message, showMessage = true) { if (showMessage) { ElMessage.success(message) } } const isHttpError = (error) => { return error instanceof HttpError } export { HttpError, handleError, isHttpError, showError, showSuccess }