Express-Error Handling

这篇博客介绍了如何在Express中进行错误处理。新建了appError.js文件用于自定义错误,包括状态码和错误信息。在index.js中引入appError,并在异步操作中使用,确保即使发生错误,程序仍能继续执行。当遇到数据库如MongoDB的错误时,通过Try-Catch结构统一捕获并封装错误,例如Mongoose的错误打印。
摘要由CSDN通过智能技术生成

新建appError.js

可以获得自己设置的状态码和报错信息

class AppError extends Error {
   
    constructor(message, status) {
   
        super();
        this.message = message;
        this.status = status;
    }
}
module.exports = AppError;

index.js:

  • 导入appError:
const AppError = require('./AppError');
  • 使用:
const verifyPassword = (req, res, next) => {
   
    const {
    password } = req.query;
    if (password === 'chickennugget') {
   
        next();
    }
    throw new AppError('password required', 401);
    // res.send("PASSWORD NEEDED!")
    // throw new AppError('Password required!', 400)
}

app.get('/admin', (req, res) => {
   
    throw new AppError('You are not an Admin!', 403)
})

//写在最后
//status = 500, message = 'Something Went Wrong' 为默认状态
app.use((err, req, res,
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值