javascript - 在 express js 中将中间件捆绑到一个异步错误处理程序中(中央错误处理)
问题描述
我已经设置了如下的 api 端点
// doesn't require to go through auth middleware
app.get('/api/list', asyncErrorHandler(async (req, res) => {
// stuffs here
if (somethingWrong)
throw new Error("Something is wrong for sure")
else
res.status(200).send("Only List for you okay?")
}, false))
// requires to go through auth middleware
app.get('/api/show', asyncErrorHandler(async (req, res) => {
// stuffs here
if (somethingWrong)
throw new Error("Something is wrong for sure")
else
res.status(200).send("Here you go my dude! wink")
}))
// auth function
const auth = async (req, res, next) => {
//stuffs here
if(notProperUser) throw new Error("Bruh! You not supposed to be here!")
else next()
}
如何设置我的asyncErrorHandler
以便在块中发生以下事情?
const asyncErrorHandler = (fn, authParam = true) => (req, res, next) => {
// if authPram = true
// promise resolve auth then = > fn = > if error is thrown,
// catch error and break promise chain
// log e and return res.status(e.status).send("error")
// (assume we have a custom error with status)
// else
// same as if block but skip auth and only execute fn callback function
// need to be executed
}
不能使用以下
app.get('/api/show', auth, asyncErrorHandler(async (req, res) => {
// stuffs here
if (somethingWrong)
throw new Error("Something is wrong for sure")
else
res.status(200).send("Here you go my dude! wink")
}))
因为在auth
layer 抛出的错误不会被asyncErrorHandler
. auth
需要捕获错误,asyncErrorHandler
因为需要对所有层进行集中错误处理。
我想知道我们如何使用以下内容来容纳authParam
标志和额外的auth
中间件
const asyncErrorHandler = (fn, authParam = true) => (req, res, next) => {
// following code is incomplete - MISSING
// authParam check and based on that
// resolve auth and fn TWO promises sequentially
// if auth throws error fn should NOT execute
// and error at auth needs to be caught
// then sent to the client
Promise.resolve(fn(req, res, next)).catch((e) => {
res.status(e.status).send("Error")
})
}
我该如何做类似上面的事情,以检查authParam
并基于该解决方案auth
并fn
相应地?上述代码需要哪些更改?
解决方案
推荐阅读
- powerbi - 如何将 Power BI 中的最大值和平均值与筛选器结合使用
- web-scraping - 我如何更改 Scrapy 以在洋葱链接上爬行?
- android - Android - WorkManager 强制 UniqueWork 在被退避策略延迟时触发?
- sql - 无法使用 SQL 脚本查找哪个客户购买了 iphone 或 HTC
- python - 如何在 django 管理中将日期层次结构限制为年?
- java - 如何将最新图像显示到 ImageView 另一个活动?
- python - 如何多次运行一个函数并返回不同的结果python
- sql - Left Join 在匹配数据上返回 NULL
- java - Object2ObjectOpenHashMap put 方法中的 Nullpointerexception
- rust - async_std::sync::Arc 的目的是什么?