【问题标题】:How do you properly stop execution of an express.js endpoint?如何正确停止 express.js 端点的执行?
【发布时间】:2022-02-07 16:17:27
【问题描述】:

我有一个运行良好的中间件错误处理程序,但在处理承诺时,next(err) 和 return 和 return next(err) 似乎不会停止执行。发现错误时停止执行我的代码的正确方法是什么?

供参考:在这种情况下,err 是标准的错误类。

我认为您不需要 userProvider.fetchFriends 中的代码来帮助解决此问题,但如果有误请告诉我。

  const uid = req.query.steamUserId;

  //Use the userProvider to get steam friend data
  const friendData = await userProvider.fetchFriends(uid)
  .catch(err => {
    return next(err); //Does not stop execution. Why? just next(err) doesn't either.
  });

  //Putting this after every catch works but seems very stupid. How do I avoid this?
  if(res.writableEnded) 
    return;

  ...Other code that runs but causes errors
}

【问题讨论】:

  • 为什么要混合 async/await .then/.catch?鉴于您正在等待承诺,请使用 try/catch - 在回调中返回从不与在外部函数中返回相同。
  • 将 await 放入一个“正常”的 try-catch 中

标签: javascript node.js express


【解决方案1】:

这里有两个问题。

首先:next() 明确地继续到下一个中​​间件或端点。

要完成对请求的处理,请发送响应。

const middleware = (req, res, next) => {
    if (something(req)) {
        next();
    } else {
        res.status(500).json({ ok: false, msg: "some error message" });
    }
}

第二:你需要仔细观察你的异步逻辑。

你不能:

  1. 触发一些异步的东西
  2. 发送回复
  3. 异步功能完成时发送不同的响应

您只能对请求发送一个响应。

要么:

  • 不要在catch 块中调用nextres.something,只在内部记录错误
  • 不要在 Promise 处理之外调用 nextres.something 并将其移动到 then 处理程序(您可能希望切换到使用 async/await让你的逻辑更容易理解)

【讨论】:

    【解决方案2】:

    问题是我将 async/await 与 .then/.catch 混合在一起。需要使用 try/catch。

    ty @jonsharpe

    export const getSteamFriends = async (req, res, next) => {
      try{
        const uid = req.query.steamUserId;
    
        //Use the userProvider to get steam friend data
        const friendData = await userProvider.fetchFriends(uid);
      
        //more code in the middle
      } catch(e) {
        return next(e);
      }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-26
      • 2014-07-28
      • 2020-01-24
      • 2015-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多