快速错误处理——应用程序在抛出错误时崩溃,而不是进入错误处理程序



我的节点应用程序有一个问题。我设置了一个错误处理中间件,当我在控制器中抛出错误时,应用程序崩溃,而不是进入错误处理程序。

ErrorHandler.js

const mongoose = require("mongoose");
exports.ErrorHandler = (err, req, res, next) => {
console.log(err);
if (err instanceof mongoose.Error.ValidationError) {
return res.status(422).json(err.errors);
}
if (err instanceof mongoose.Error.CastError) {
return res.status(404).json({ message: "Resource not found" });
}
return res.status(500).json(err);
};

AuthController.js

static init = async (req, res) => {
throw new NotFoundError("Not found");
}

我不知道你是如何调用ErrorHandler,如果你使用express,但我认为你正在使用它。虽然我认为我可以给你一个简单的例子使用ErrorHandler作为中间件:

function errorHandler(error, req, res, next) {
res.status(error.status || 500);
res.send({
error: {
message: error.message,
},
});
}
// Error-handling middleware 
app.use(errorHandler);
//example
app.get('/', function (req, res, next) {
next(new Error('Error for understanding the ErrorHandler'));
});

在这个例子中你的应用不会崩溃。

请阅读这个官方指南来完全了解它是如何工作的:https://expressjs.com/en/guide/error-handling.html

你必须在你的控制器中使用try和catch。然后在catch函数中按如下方式调用next:

static init = async (req, res) => {
try {
throw new NotFoundError("Not found");
} catch(error) {
next(error)
}
}

最新更新