Javascript 返回错误后执行Node.js Restify代码
我在Restify路由中配置了一个路由器处理程序。在该处理程序中,我调用一个自定义模块,在其中执行一些错误检查。当遇到错误条件时,我的代码将返回next(err)。我在浏览器中看到错误消息,但出于某种原因,我的代码也会在之后继续执行 Restify路由器处理程序Javascript 返回错误后执行Node.js Restify代码,javascript,node.js,express,restify,Javascript,Node.js,Express,Restify,我在Restify路由中配置了一个路由器处理程序。在该处理程序中,我调用一个自定义模块,在其中执行一些错误检查。当遇到错误条件时,我的代码将返回next(err)。我在浏览器中看到错误消息,但出于某种原因,我的代码也会在之后继续执行 Restify路由器处理程序 HttpHandlers.prototype.callHttp = function(req, res, next) { myUtils.checkInputRules(req, res, next, handlerConfig.inp
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
}
您没有包含完整的代码,但问题可能是这样的:当您从函数返回时,从哪个函数返回很重要。例如:
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
}
你能抛出一个错误吗?@Thomas,为了排除问题,我将return next(err)复制到调用函数中,它按预期工作,然后我将其移动到checkInputRules的顶部,我得到了问题。我从Restify API和Stackoverflow上的答案中了解到,return next(err)是在Restify和Express中设置错误的正确方法。你能抛出一个错误吗?@Thomas,为了排除问题,我将return next(err)复制到调用函数中,它按预期工作,然后我把它移到checkInputRules的顶部,我得到了这个问题。我从restifyapi和Stackoverflow的答案中了解到,returnnext(err)是在Restify和Express中设置错误的正确方法。