exception的通用捕获版本?

我有一个sequelize数据库validation数据并抛出错误。

我知道我可以做这样的事情来捕捉和输出我的错误:

User.build() .catch(Sequelize.ValidationError, function (err) { // respond with validation errors return res.status(422).send(err.errors); }) .catch(function (err) { // every other error return res.status(400).send({ message: err.message }); 

但我不想把它添加到每一个请求,是否有一些通用的方法来捕捉这些错误?

您可以将自定义方法添加到req (或res ),以解决承诺并处理任何错误:

 app.use((req, res, next) => { req.resolve = (promise) => { return promise.catch(Sequelize.ValidationError, err => { // respond with validation errors return res.status(422).send(err.errors); }).catch(err => { // every other error return res.status(400).send({ message: err.message }); }); }); next(); }); 

用法(假设上面的中间件被添加到路由之前):

 router.post('/user', (req, res) => { req.resolve(User.build()).then(user => res.json(user)); }); 

ES.next版本(2016)

你可以使用asynchronous函数throw使用从官方strongloop网站复制的包装函数:

 let wrap = fn => (...args) => fn(...args).catch(args[2]); 

然后在你的路由器/控制器中做这样的function:

 router.post('/fn/email', wrap(async function(req, res) { ...throw new Error(); } 

终于有了一个正常的捕获所有错误的中间件:

 app.use(function(err, req, res, next) { console.log(err); } 

显然,为了这个工作,你需要目前的babel transpiler