【Express】自定义错误码和通用返回对象

自定义错误码:

// 自定义错误
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,
    }
}

由于默认错误捕获不能捕获异步错误,所以需要安装express-async-errors:

https://www.npmjs.com/package/express-async-errors

在 app.js 中引入使用

// 捕获异步错误
require("express-async-errors")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

秀秀_heo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值