0

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."));
...
user994165
  • 9,146
  • 30
  • 98
  • 165
  • Can you just throw an error ? – Thomas Sep 19 '16 at 22:51
  • @Thomas, to rule things out, I copied the return next(err) to the calling function, and it works as expected, then I moved it to the top of checkInputRules and I get the issue. My understanding from the Restify API and answers here on Stackoverflow is that return next(err) is the proper way to set errors in Restify and Express. – user994165 Sep 19 '16 at 22:54

1 Answers1

2

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
}
rsp
  • 107,747
  • 29
  • 201
  • 177