我在 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."));
...
最佳答案
您没有包含完整的代码,但问题可能是这样的:当您从函数返回时,从哪个函数返回很重要。例如:
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
}
关于javascript - 返回错误后执行 Node.js Restify 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39583014/