2016-06-28 138 views
1

我有一些錯誤處理中間件定義和返回承諾的路線。但是,當承諾出現錯誤時,我必須在每次承諾後手動附加.catch(err => next(err))。雖然它不是問題,ExpressJs看看路由是否返回承諾並且自動調用錯誤處理中間件是不明智的。ExpressJS:承諾和錯誤處理中間件

我現在縮短代碼:

// errorHandlers.js 
function sequelizeValidationError (err, req, res, next) { 
    if (err.name && err.name == 'SequelizeValidationError') 
    res.status(400).send(err.errors) 
    else next(err) 
} 

// auth.js 
router.post ('/register', middleware.isNotAuthenticated, (req, res, next) => { 
    const { email, password, name } = req.body; 

    return models.User.find({where : { email }}).then(user => { 
    if (user) { 
     if (user.password == password) sendToken(user.id, res); 
     else res.sendStatus(401); 
    } else { 
     return models.User.create({ 
     email, password, name 
     }).then(user => { 
     sendToken(user.id, res); 
     }) 
    } 
    }).catch(next) 
}) 

// index.js 
router.use('/auth', require('./auth')) 

router.use(errorHandlers.sequelizeValidationError) 

例如,目前我可以忘了寫catch在一個地方和服務器會失敗。

我錯過了什麼嗎?我怎樣才能避免每次輸入catch

+0

不確定是否切換框架是您的選擇,但http://koajs.com/原生地使用promise。寫一個捕捉中間件是微不足道的koa.js – Herku

+0

@Herku,我不能爲這個項目,但會看看koa爲下一個項目肯定。看看它,看起來很容易使用[koa-router](https://github.com/alexmingoia/koa-router) –

+1

有許多模塊可以爲Express提供承諾支持,例如['promise- express-router'](https://github.com/ufo22940268/promise-express-router)和['express-ko'](https://github.com/ex-machine/express-ko)(這也是恰好爲快車實施了一些Koa-goodness)。也許它是有用的。 – robertklep

回答