首页 > 解决方案 > 在 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")
}))

因为在authlayer 抛出的错误不会被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并基于该解决方案authfn相应地?上述代码需要哪些更改?

标签: javascriptnode.jsapiexpressmiddleware

解决方案


推荐阅读