javascript - 返回错误后执行 Node.js Restify 代码

标签 javascript node.js express restify

我在 Restify 路由中配置了一个路由器处理程序。在该处理程序中,我调用一个自定义模块,在其中进行一些错误检查。当我遇到错误情况时,我的代码返回下一个(错误)。我在浏览器中看到错误消息,但由于某种原因,我的代码在那之后也继续执行。

Restify 路由器处理程序

HttpHandlers.prototype.callHttp = function(req, res, next) {
myUtils.checkInputRules(req, res, next, handlerConfig.inputRules);

//This code is getting executed:
logger.debug("Updated ...

被调用的函数:

myUtils.checkInputRules = function checkInputRule(req, res, next, inputRules) {
...
        } else {
            if (inputRule.ifFalse) {
                var evalStr = inputRule.ifFalse;
                if (evalStr != null) {
                    logger.debug("Executing condition.iFalse: "+evalStr);

                    //The code is itting this location
                    return next(new Error("Internal Error: Failure."));
...

最佳答案

您没有包含完整的代码,但问题可能是这样的:当您从函数返回时,从哪个函数返回很重要。例如:

function handler(req, res, next) {
  helper(req, res, next);
  // this will still run
}

function helper(req, res, next) {
  if (something) return next();
}

在这里,您似乎正在运行 myUtils.checkInputRules 函数,并且您正在从 myUtils.checkInputRules 函数返回,但实际上并不是从 返回HttpHandlers.prototype.callHttp 因此 myUtils.checkInputRules(req, res, next, handlerConfig.inputRules); 之后的所有内容仍然会执行。

您没有显示完整的代码,但看起来都是同步的。在这种情况下,你可以这样做:

function handler(req, res, next) {
  if (helper(req, res, next)) {
    // next() was already called
  } else {
    // do something else - next() not called yet...
  }
}

function helper(req, res, next) {
  if (something) {
    next();
    // indicate that next() was already called: 
    return true;
  }
  // possibly do something else
}

关于javascript - 返回错误后执行 Node.js Restify 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39583014/

相关文章:

node.js - 如何升级npm版本到最新? Ubuntu显示安装成功但不升级版本

node.js - ES6模块导入typescript的绝对路径

javascript - Selectpicker(引导选择)不起作用,显示禁用菜单?

javascript - 从字符串创建 svg 元素

javascript - Bootstrap Carousel 幻灯片会扰乱网站的元素和内容

javascript - MEAN 堆栈,我不想使用 Jade,我怎么只使用 HTML

node.js - 如何使用 ExpressJS 4 上传文件?

javascript - AngularJS、requireJS 和 ngRoute

javascript - 如何使用 Babel 和预设启动 PM2 Node JS

javascript - 是否可以在我的 Jest 测试套件中创建一个 Express.js 服务器?