/** * 用于规范化向用户返回的错误信息。信息与状态码皆为枚举类型,以便前端进行 i18n、保证错误信息的准确性, * 同时保证返回的格式符合 HTTP 规范。 */ class HttpError extends Error { /** * 创建一个新的 HTTP 错误。 * @param message 错误的消息。 * @param status 错误的状态码。 * @param context 错误的上下文。 */ constructor(message: ErrorDescEnum, status: 400 | 401 | 403 | 404 | 500, context?: string[]) { super(message); this.status = status; if (context) this.context = context; } /** * 错误的状态码。 */ status: 400 | 401 | 403 | 404 | 500; /** * 错误上下文,一般指示错误适用的字段。 */ context?: string[]; } /** * 错误描述的枚举。 */ enum ErrorDescEnum { /** * 必填字段缺失。通常与 HTTP 状态码 400 Bad Request 一起使用。 */ required_fields_missing = 'required_fields_missing', /** * 字段格式不正确。通常与 HTTP 状态码 400 Bad Request 一起使用。 */ invalid_field_format = 'invalid_field_format', /** * 未知错误。通常与 HTTP 状态码 500 Internal Server Error 一起使用。 */ unknown_issues = 'unknown_issues', /** * 项目已存在。通常与 HTTP 状态码 400 Bad Request 一起使用。 */ item_exists = 'item_exists', /** * 项目不存在。通常与 HTTP 状态码 404 Not Found 一起使用。 */ item_not_found = 'item_not_found', /** * 未授权。通常与 HTTP 状态码 401 Unauthorized 一起使用。 */ unauthorized = 'unauthorized', /** * 关联项目不存在。例如,创建新收据时,指定的付款人不存在。通常与 HTTP 状态码 400 Bad Request 一起使用。 */ related_item_not_found = 'related_item_not_found' } export { HttpError, ErrorDescEnum }