错误处理中间件 thenables nodejs express
Error handling middleware thenables nodejs express
所以我有这个错误处理程序中间件
class ErrorHandler extends Error {
constructor(statusCode, message) {
super();
this.statusCode = statusCode;
this.message = message;
}
}
const handleError = (err, res) => {
const { statusCode, message } = err;
res.status(statusCode).json({
status: "error",
statusCode,
message: "resource not found"
});
};
module.exports = {
ErrorHandler,
handleError
}
在 index.js
中调用它
app.use((err, req, res, next) => {
handleError(err, res);
})
而且我想在我的所有方法中使用它,但我不知道如何将它与 catch 一起使用。对我来说似乎不是很清楚。对于 404 错误工作得很好,但如果我试图抛出 500 错误,例如一个 ReferenceError 我不知道如何使用我的函数。
exports.getAll = function(req, res, next) {
User.find({})
.exec()
.then(users => {
if (users.length === 0) {
throw new ErrorHandler(404, "No users found");
} else {
res.json(users);
next;
}
})
.catch(error => {
res.status(500).send({
message: "Error finding users",
error: error
})
})
};
在 .catch 中,我想像在 .then 中那样使用我的错误处理程序
在 catch 块中,您可以像 next(err)
一样使用 next 去处理错误
.catch(err=>{
let error = new ErrorHandler(500,"Error finding users");
next(error);
})
所以我有这个错误处理程序中间件
class ErrorHandler extends Error {
constructor(statusCode, message) {
super();
this.statusCode = statusCode;
this.message = message;
}
}
const handleError = (err, res) => {
const { statusCode, message } = err;
res.status(statusCode).json({
status: "error",
statusCode,
message: "resource not found"
});
};
module.exports = {
ErrorHandler,
handleError
}
在 index.js
中调用它app.use((err, req, res, next) => {
handleError(err, res);
})
而且我想在我的所有方法中使用它,但我不知道如何将它与 catch 一起使用。对我来说似乎不是很清楚。对于 404 错误工作得很好,但如果我试图抛出 500 错误,例如一个 ReferenceError 我不知道如何使用我的函数。
exports.getAll = function(req, res, next) {
User.find({})
.exec()
.then(users => {
if (users.length === 0) {
throw new ErrorHandler(404, "No users found");
} else {
res.json(users);
next;
}
})
.catch(error => {
res.status(500).send({
message: "Error finding users",
error: error
})
})
};
在 .catch 中,我想像在 .then 中那样使用我的错误处理程序
在 catch 块中,您可以像 next(err)
.catch(err=>{
let error = new ErrorHandler(500,"Error finding users");
next(error);
})