2016-09-19 29 views
0

我在Restify路由中配置了一個路由器處理程序。在那個處理程序中,我打電話給一個自定義模塊,在那裏我做了一些錯誤檢查。當我遇到錯誤情況時,我的代碼返回下一個(err)。我在瀏覽器中看到錯誤消息,但由於某種原因,我的代碼也在此後繼續執行。Node.js返回錯誤後執行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.")); 
... 
+0

你可以拋出一個錯誤嗎? – Thomas

+0

@Thomas,爲了解決這個問題,我將下一個返回值(err)複製到調用函數中,並且它按預期工作,然後將它移動到checkInputRules的頂部,並且我得到該問題。我對Restify API的理解和對Stackoverflow的回答是:return next(err)是在Restify和Express中設置錯誤的正確方法。 – user994165

回答

2

你沒有包括整個代碼,但該問題可能是這樣的:當你從一個函數返回,重要的是你從哪個功能返回。例如:

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 
} 
相關問題