"use strict"; const common_vendor = require("../common/vendor.js"); const ERROR_CODE_MAP = { 401: "登录已过期,请重新登录", 403: "没有权限执行此操作", 404: "请求的资源不存在", 500: "服务器错误,请稍后重试", 502: "网关错误", 503: "服务不可用,请稍后重试", 504: "网关超时" }; const BUSINESS_ERROR_CODE_MAP = { 10001: "用户名或密码错误", 10002: "账号已被禁用", 10003: "验证码错误", 10004: "操作过于频繁,请稍后再试" // 添加更多业务错误码... }; class ErrorHandler { constructor() { this.lastMessage = ""; this.lastTime = 0; } /** * 显示错误提示 * @param {string} message - 错误信息 * @param {number} duration - 显示时长 */ showError(message, duration = 2e3) { if (this.lastMessage === message && Date.now() - this.lastTime < 3e3) { return; } common_vendor.index.showToast({ title: message, icon: "none", duration }); this.lastMessage = message; this.lastTime = Date.now(); } /** * 处理HTTP错误 * @param {number} statusCode - HTTP状态码 * @param {Object} response - 响应对象 * @returns {Error} - 格式化的错误对象 */ handleHttpError(statusCode, response) { const errorMsg = ERROR_CODE_MAP[statusCode] || `网络请求错误:${statusCode}`; this.showError(errorMsg); const error = new Error(errorMsg); error.code = statusCode; error.response = response; if (statusCode === 401) { this.handleUnauthorized(); } return error; } /** * 处理业务错误 * @param {Object} data - 业务响应数据 * @returns {Error} - 格式化的错误对象 */ handleBusinessError(data) { const errorMsg = BUSINESS_ERROR_CODE_MAP[data.code] || data.msg || "请求失败"; this.showError(errorMsg); const error = new Error(errorMsg); error.code = data.code; error.data = data; return error; } /** * 处理网络请求失败 * @param {Object} err - 原始错误对象 * @returns {Error} - 格式化的错误对象 */ handleRequestFail(err) { let errorMsg = "网络请求失败,请检查网络连接"; if (err.errMsg) { if (err.errMsg.includes("timeout")) { errorMsg = "请求超时,请检查网络连接"; } else if (err.errMsg.includes("abort")) { errorMsg = "请求已取消"; } else if (err.errMsg.includes("SSL")) { errorMsg = "网络安全证书错误"; } } this.showError(errorMsg); const error = new Error(errorMsg); error.original = err; return error; } /** * 处理未授权错误(401) */ handleUnauthorized() { common_vendor.index.removeStorageSync("token"); common_vendor.index.removeStorageSync("userInfo"); setTimeout(() => { common_vendor.index.navigateTo({ url: "/pages/login/login" }); }, 1500); } /** * 记录错误日志 * @param {Error} error - 错误对象 * @param {string} source - 错误来源 */ logError(error, source = "unknown") { console.error(`[${source}] Error:`, error); } } const errorHandler = new ErrorHandler(); exports.errorHandler = errorHandler;