自定义错误码:
// 自定义错误
const {formatResponse} = require("./tool");class ServiceError extends Error {/**** @param message 自定义错误信息* @param code 自定义错误码*/constructor(message, code) {super(message);this.code = code;}/*** 将错误信息格式化为JSON* @returns {{msg, code, data}}*/toResponseJSON(){return formatResponse(this.code,this.message, {})}
}
// 文件上传错误
exports.UploadError = class UploadError extends ServiceError {constructor(message) {super(message, 413);}
}
// 禁止访问错误
exports.ForbiddenError = class ForbiddenError extends ServiceError {constructor(message) {super(message, 401);}
}
// 验证错误
exports.ValidationError = class ValidationError extends ServiceError {constructor(message) {super(message, 406);}
}
// 无资源错误
exports.NotFoundError = class NotFoundError extends ServiceError {constructor(message) {super(message, 404);}
}
// 未知错误
exports.UnknownError = class UnknownError extends ServiceError {constructor() {super('server interval error', 500);}
}
module.exports.ServiceError = ServiceError;
自定义通过返回对象:
/*** 生成通用返回对象* @param code 自定义状态码* @param msg 返回信息* @param data 返回数据* @returns {{msg, code, data}}*/
module.exports.formatResponse = function (code, msg, data) {return {code: code,msg: msg,data: data,}
}