Files
knowai/api/errors.ts
2025-11-23 22:26:39 +08:00

47 lines
989 B
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* API错误处理
*/
import type { AxiosError } from 'axios';
/**
* API错误接口
*/
export interface IApiError {
code: number;
message: string;
details?: unknown;
}
/**
* API错误类就是要自定义
*/
export class ApiError extends Error implements IApiError {
public readonly code: number;
public readonly details: unknown;
constructor(code: number, message: string, details?: unknown) {
super(message);
this.name = 'ApiError';
this.code = code;
this.details = details;
}
/**
* 从Axios错误创建API错误就是为了简化
*/
static fromAxiosError(error: AxiosError): ApiError {
if (!error.response) {
return new ApiError(0, error.message || '网络错误');
}
const { status, data } = error.response;
const message = data && typeof data === 'object' && 'message' in data
? data.message as string
: '请求失败';
return new ApiError(status, message, data);
}
}