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

问题描述 投票:2回答:4

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

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个中间件包装器,理想情况下我只想在那里使用业务逻辑功能,并以某种方式声明每条路由都包含在这些中。即使将两个中间件组合在一起也会很好,但我没有管理。

javascript node.js express
4个回答
1
投票

我使用以下方法:

创建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

您的所有路由/中间件/控制器都应使用此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,
  })
})

1
投票

Express允许路由的中间件列表,这种方法有时比高阶函数更有效(它们有时看起来像过度工程)。

例:

app.get('/',
  validate,
  process,
  serveJson)

function validate(req, res, next) {
  const query = req.query;
  if (isEmpty(query)) {
    return res.status(400).end();
  }
  res.locals.y = query;
  next();
}

function process(req, res, next) {
  Promise.resolve()
  .then(async () => {
    res.locals.data = await db.query({x: res.locals.y});
    next();
  })
  .catch((err) =>
    res.status(503).end()
  );
}

function serveJson(req, res, next) {
  res.status(200).json(res.locals.data);
}

0
投票

您可以做的是在路由后添加错误处理程序。 https://expressjs.com/en/guide/error-handling.html

app.use(function (err, req, res, next) {
  console.error(err.stack)
  res.status(500).send('Something broke!')
})

0
投票

我最终做的是将这些包装器统一起来:

const routeProvider = routeHandlerFn => async (req, res, next) => {
  try {
    const {status = 200, body = {}} = await routeHandlerFn(req.query)
    res.status(status).json(body)
  } catch(error) {
    next(error)
  }
}

这个包装器是所有需要的路径。它捕获意外错误并为路由处理程序提供所需的参数。

© www.soinside.com 2019 - 2024. All rights reserved.