简体   繁体   中英

Node.js Restify code is executed after returning error

I have a router handler configured in a Restify route. In that handler I make a call to a custom module where I do some error checking. When I hit an error condition, I my code returns next(err). I see the error message in the browser, but for some reason my code continues executing after that as well.

The Restify router handler

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

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

The function being called:

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."));
...

You didn't include the entire code but the issue may be something like this: When you return from a function, it is important which function you return from. For example:

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

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

Here it seems that you are running the myUtils.checkInputRules function and you are returning from your myUtils.checkInputRules function, but you are not actually returning from HttpHandlers.prototype.callHttp so everything after myUtils.checkInputRules(req, res, next, handlerConfig.inputRules); is still executed.

You didn't show the entire code but it seems all synchronous. In that case you can do something like this:

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM