Files
xingrin/frontend/lib/error-handler.ts

131 lines
3.2 KiB
TypeScript
Raw Normal View History

2025-12-12 18:04:57 +08:00
/**
*
*
* 24
* -
* -
* -
*/
import { toast } from "sonner"
/**
* API
*/
export interface ApiError {
response?: {
data?: unknown
}
message?: string
}
/**
* mutation
* @param error
* @param userMessage
* @param toastId toast ID
*/
export function handleMutationError(
error: unknown,
userMessage: string,
toastId?: string
) {
// 关闭加载提示(如果有)
if (toastId) {
toast.dismiss(toastId)
}
// 控制台打印详细错误信息
console.error('操作失败:', error)
console.error('后端响应:', (error as ApiError)?.response?.data || error)
// 显示前端自定义的用户友好错误消息
toast.error(userMessage)
}
/**
* query
* @param error
* @param userMessage
*/
export function handleQueryError(error: unknown, userMessage: string) {
// 控制台打印详细错误信息
console.error('查询失败:', error)
console.error('后端响应:', (error as ApiError)?.response?.data || error)
// 显示前端自定义的用户友好错误消息
toast.error(userMessage)
}
/**
*
* @param response
* @param successMessage
* @param toastId toast ID
*/
export function handleSuccess(
response: unknown,
successMessage: string,
toastId?: string
) {
// 关闭加载提示(如果有)
if (toastId) {
toast.dismiss(toastId)
}
// 控制台打印成功信息
console.log('操作成功')
console.log('后端响应:', response)
// 显示前端自定义的成功消息
toast.success(successMessage)
}
/**
*
* @param response
* @param warningMessage
* @param toastId toast ID
*/
export function handleWarning(
response: unknown,
warningMessage: string,
toastId?: string
) {
// 关闭加载提示(如果有)
if (toastId) {
toast.dismiss(toastId)
}
// 控制台打印信息(仅在开发环境)
if (process.env.NODE_ENV === 'development') {
console.log('操作部分成功')
console.log('后端响应:', response)
}
// 显示前端自定义的警告消息
toast.warning(warningMessage)
}
/**
*
* @param response API
* @returns
*/
export function isSuccessResponse(response: unknown): boolean {
return (response as { state?: string })?.state === 'success'
}
/**
*
* @param response API
* @param defaultValue
* @returns
*/
export function extractData<T>(response: unknown, defaultValue: T): T {
if (isSuccessResponse(response) && (response as { data?: T }).data) {
return (response as { data: T }).data
}
return defaultValue
}