gpt4 book ai didi

javascript - express.js 异步路由器和错误处理

转载 作者:搜寻专家 更新时间:2023-11-01 00:48:19 24 4
gpt4 key购买 nike

我有一个异步函数作为路由处理程序,我希望将错误处理为某种中间件。这是我的工作尝试:

router.get(
"/",
asyncMiddleware(
routeProviderMiddleware(
async ({ y }) => ({
body: await db.query({x: y})
})
)
)
)

// This is the middleware that catches any errors from the business logic and calls next to render the error page
const asyncMiddleware = fn =>
(req, res, next) => {
Promise.resolve(fn(req, res, next))
.catch(next)
}

// This is a middleware that provides the route handler with the query and maybe some other services that I don't want the route handler to explicitly access to
const routeProviderMiddleware = routeHandlerFn => async (req, res) => {
const {status = 200, body = {}} = await routeHandlerFn(req.query)
res.status(status).json(body)
}

我努力的是一种使路由声明更清晰的方法——我不想要那里的 2 个中间件包装器,理想情况下我只想要那里的业务逻辑功能,并以某种方式声明每条路由都被包装在这些。甚至将这两个中间件组合在一起也很好,但我没有成功。

最佳答案

我使用以下方法:

创建 asyncWrap 作为辅助中间件:

const asyncWrap = fn =>
function asyncUtilWrap (req, res, next, ...args) {
const fnReturn = fn(req, res, next, ...args)
return Promise.resolve(fnReturn).catch(next)
}

module.exports = asyncWrap

你所有的路由/中间件/ Controller 都应该使用这个asyncWrap来处理错误:

router.get('/', asyncWrap(async (req, res, next) => {
let result = await db.query({x: y})
res.send(result)
}));

app.js,最后一个中间件会收到所有asyncWrap的错误:

// 500 Internal Errors
app.use((err, req, res, next) => {
res.status(err.status || 500)
res.send({
message: err.message,
errors: err.errors,
})
})

关于javascript - express.js 异步路由器和错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55887918/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com