Node.js 返回错误后执行Restify代码
Node.js Restify code is executed after returning error
我在 Restify 路由中配置了一个路由器处理程序。在该处理程序中,我调用了一个自定义模块,我在其中进行了一些错误检查。当我遇到错误情况时,我的代码 returns next(err)。我在浏览器中看到了错误消息,但出于某种原因,我的代码在那之后也继续执行。
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."));
...
您没有包括整个代码,但问题可能是这样的:当您从一个函数 return 时,您 return 来自哪个函数很重要。例如:
function handler(req, res, next) {
helper(req, res, next);
// this will still run
}
function helper(req, res, next) {
if (something) return next();
}
这里看起来你是 运行 myUtils.checkInputRules
函数,你是 return 来自你的 myUtils.checkInputRules
函数,但你实际上不是 return 从 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
}
我在 Restify 路由中配置了一个路由器处理程序。在该处理程序中,我调用了一个自定义模块,我在其中进行了一些错误检查。当我遇到错误情况时,我的代码 returns next(err)。我在浏览器中看到了错误消息,但出于某种原因,我的代码在那之后也继续执行。
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."));
...
您没有包括整个代码,但问题可能是这样的:当您从一个函数 return 时,您 return 来自哪个函数很重要。例如:
function handler(req, res, next) {
helper(req, res, next);
// this will still run
}
function helper(req, res, next) {
if (something) return next();
}
这里看起来你是 运行 myUtils.checkInputRules
函数,你是 return 来自你的 myUtils.checkInputRules
函数,但你实际上不是 return 从 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
}