Skip to content

Commit

Permalink
✨ feat: add error Response func
Browse files Browse the repository at this point in the history
  • Loading branch information
arvinxx committed Aug 19, 2023
1 parent 8b6e2ba commit ac3e036
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { ErrorResponse, ErrorType } from '@/types/error';

const getStatus = (errorType: ErrorType) => {
// TODO: Add ErrorSwitch
// eslint-disable-next-line no-empty
switch (errorType) {
}

return errorType;
};

/**
* 创建一个错误响应对象
* @param {ErrorType} errorType - 错误类型
* @param body - 响应体数据
* @returns {Response} - 错误响应对象
*/
export const createErrorResponse = (errorType: ErrorType, body?: string | object) => {
// 获取错误类型对应的状态码
const statusCode = getStatus(errorType);

// 构造错误响应数据
const data: ErrorResponse = { body, errorType };

// 创建并返回错误响应对象
return new Response(JSON.stringify(data), { status: statusCode });
};
22 changes: 22 additions & 0 deletions src/types/error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
export enum ErrorType {
// ******* 业务错误语义 ******* //

// ******* 客户端错误 ******* //
BadRequest = 400,
Unauthorized = 401,
Forbidden = 403,
ContentNotFound = 404, // 没找到接口
MethodNotAllowed = 405, // 不支持
TooManyRequests = 429,

// ******* 服务端错误 ******* //
InternalServerError = 500,
BadGateway = 502,
ServiceUnavailable = 503,
GatewayTimeout = 504,
}

export interface ErrorResponse {
body: any;
errorType: ErrorType;
}

0 comments on commit ac3e036

Please sign in to comment.