在辅助函数中调用下一个?

时间:2016-07-16 20:39:43

标签: node.js express

我正在尝试设置一个简单的系统来渲染用户输入错误并在快递中停止传播,这是我到目前为止所做的:

routingFunction= (req, res, next) {
  //setting up a test in express-validator
  var test = req.assert('access_token', 'required').notEmpty();
  isValid(test, next);
  //non error stuff
}

isValid = (tests, next) => {
    //some more code here, that checks if any errors were found and save tem to the array errors.
    if(errors.length > 0){
        return next(new Error());
    }
};

 //a middleware that catches errors:
 app.use((err, req, res, next) => {
     res.json('error').end();
 });

我的问题是它在我调用Next(new Error());时不会停止传播,我可以从isValid返回true / false然后返回next(new Error()),但这会添加我的控制器有很多膨胀,有没有更好的方法从辅助函数中做到这一点?

2 个答案:

答案 0 :(得分:0)

在主路线档案中,例如 public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button2_Click(object sender, EventArgs e) { MyClass mc = new MyClass(); mc.navigate(); } }

routes/index.js

// Set of func(req, res, next) let v = require('validator'); // middleware-validators let user = require('user'); // routes for user ... app.get('/smth-route-of-user', v.isTokenSet, v.isEmail, ..., user.get)

middlewares/validator.js

您可以将验证者加入一个,例如checkUser(),并且只在路由中使用一个。

let v = require('validator-func-list'); ... exports.isTokenSet = function (req, res, next) { if (v.isValid(req.body.token)) next(); // Forwarding to next middleware. In our route next() called v.isEmail else next(new Error('Token is empty')); // Stop route chain and call error-middleware; } exports.isEmail = function (req, res, next) { ...

middlewares/errorHandler.js

module.exports = function (err, req, res, next) { let msg = err.message; // Here we see 'Token is empty'; if (req.xhr) res.json(msg); else res.render('error_page.html', {message: msg, ...}); // Here we can call next(err) to forwarding error to next errorHandler. In example below it was errorHandler2. } 中,不要忘记将错误中间件附加到应用程序。

app.js

如果您需要收集错误,则验证者必须将错误推送到app.use(require('middlewares/errorHandler')); app.use(require('middlewares/errorHandler2')); (或您想要的其他字段),并且无错误地调用req.errors。在渲染中间件中,您只需检查next()并显示正常或错误页面。

答案 1 :(得分:0)

isValid(test, next);之后始终执行的代码。下面的代码阻止它,但是imho很脏。

routingFunction = (req, res, next) {
  var test = req.assert('access_token', 'required').notEmpty();
  if (!isValid(test, next)) 
      return; // callback called by isValid. It's dust.

  //non error stuff
  ...
  next(); // callback must be called 
}

isValid = (tests, next) => {
    if(errors.length > 0){
        next(new Error());
        return false;
    }
    return true; 
};

更好用这样的

routingFunction = (req, res, next) {
  var test = req.assert('access_token', 'required').notEmpty();
  if (!isValid(test)) 
      return next (new Error('error description'));

  //non error stuff
  ...
  next();
}