Express.js API强大的错误处理解决方案



我正在尝试通过错误处理来改进下面的代码,这样我就可以在应用程序中其他相关的地方使用错误处理代码。

我有以下事件序列:

路由处理程序-->中间件-->服务-->DAO->MongoDB

我想实现一个健壮的错误处理解决方案,可以在整个应用程序中使用。

我遇到了一个问题,当DB关闭或CRUD操作失败时,DAO不会处理错误并将其传播到相关级别。我当然需要能够处理HTTP 500类型的错误,这样我的API才是健壮的。非常感谢任何建议。

作为一个遇到这样的"鲁棒错误处理解决方案";有几次(通常作为中间件实现(我强烈建议不要这样做:

不同的路线会遇到不同的边缘情况,您需要分别处理这些情况。试图创建一个";银色子弹";这将处理一切,这将从本质上更加复杂,更难维护。

此外,由于许多路由的异步性质,您可能会发现自己正在读取该错误处理程序的堆栈,而没有触发它的路由的上下文…

是的,您可以改进代码,并使用集中的错误处理程序,以防出现问题,并且错误尚未在控制器中处理。

让我们创建一个简单的应用程序来了解代码流和集中的错误处理。请注意,我在中编写以下代码StackOverflow编辑器因此直接运行可能会出现语法错误。

|- src
|-- app.js
|-- controller
|-- middleware
|-- routes

app.js

const express = require("express");
const routes = require("./routes");
const app = express();
// use /api endpoint for backend routes
app.use("/api", routes);
app.listen(8080);

middleware/error.js


function errorHandler(err, req, res, next) {
console.log("some error has occurred");
res.status(503).json({
msg: "something went wrong"
});
}
module.exports = errorHandler;

route/index.js

const express = require("express");
const router = express.Router();
const errorHandler = require("./middleware/error");
const HelloController = require("./controller/Hello.js");
router.route("/hello", HelloController);
router.use(errorHandler);
module.exports = router;

controller/Hello.js

function HelloController(req, res, next) {
try {
// Do some stuff, call dao
// Any Special Error Handling will go here
res.json({ msg: "success" });
} catch (e) {
// Any other error will call the errorHandler and send the 503 to the client thus preventing the
// server to crash
next(e); // this will call the errorHandler
}
}
module.exports = HelloController;

请求流程如下

应用Js->route/index.js->控制器/Hello.js->控制器中的IF错误a(中间件/error.js,否则b(退出

您可以在代码中添加更多基于路线的分类,如/api/public/api/private/api/admin

最新更新