新建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,