UNPKG

dqm-api-client

Version:

A Node.js client library for court booking API services including authentication, SMS verification, and court management

63 lines (53 loc) 1.74 kB
// src/utils/AppError.js class AppError extends Error { /** * 构造器支持两种调用方式: * 1. new AppError(message, name, data) * 2. new AppError(message, { name, code, data, isOperational }) */ constructor(message, arg2, arg3) { // 保持向后兼容:如果第一个参数不是字符串,设置为默认消息 if (typeof message !== 'string') { message = '未知错误'; } super(message); // 解析参数(兼容旧签名与新 options 对象) let name; let code; let data; let isOperational; if (arg2 && typeof arg2 === 'object' && typeof arg2 !== 'string') { // signature: (message, options) const opts = arg2; name = opts.name; code = opts.code; data = opts.data; isOperational = opts.isOperational; } else { // legacy signature: (message, name, data) name = arg2; data = arg3; } this.name = name || 'AppError'; this.isOperational = typeof isOperational === 'boolean' ? isOperational : true; this.data = data; // 新增稳定的错误码字段,便于程序化处理 // 优先使用显式传入的 code,否则根据 name/statusCode 生成一个默认 code this.code = code || this._defaultCodeFromName(); Error.captureStackTrace(this, this.constructor); } _defaultCodeFromName() { // 将错误名转为大写下划线形式,例如 AppError -> APP_ERROR return (this.name || 'APP_ERROR').replace(/[^a-zA-Z0-9]+/g, '_').toUpperCase(); } toJSON() { return { name: this.name, message: this.message, code: this.code, isOperational: this.isOperational, data: this.data, }; } } module.exports = AppError;