Some checks reported errors
continuous-integration/drone/push Build was killed
- 搭建 api、auth、utils 等逻辑模块 - 通过 tsc、eslint、vitest 测试验证 BREAKING CHANGE: 新镜像分支
47 lines
935 B
TypeScript
47 lines
935 B
TypeScript
/**
|
|
* 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);
|
|
}
|
|
}
|
|
|
|
|