2017-05-29 68 views
1

我正在研究Express來創建一個簡單的JSON API,並且我不確定如何組織我的輸入參數驗證和錯誤處理。錯誤可能來自驗證步驟,也可能來自數據庫訪問步驟。這是我到目前爲止有:快速錯誤處理模式

router.use(function(req, res, next) { 
    validate(req.query).then(function() { 
     next() 
    }).catch(function(e) { 
     next(e) 
    }) 
}) 

router.get("/", function(req, res, next) { 
    someDatabaseAccess(req.query).then(function(results) { 
     res.json(results) 
    }).catch(function(e) { 
     next(e) 
    }) 
}) 

router.use(function(e, req, res, next) { 

    // ... (handling specific errors) 

    res.status(400) 
    res.json(someDummyResponse(e)) 
}) 

驗證看起來是這樣的:

const validate = function(q) { 
    return new Promise(function(resolve, reject) { 
     if (q.someParameter) { 
      if (somethingWrong(q.someParameter)) { 
       reject(new Error("Something wrong!")) 
      } 
     } 
     resolve() 
    }) 
} 

這是否有道理?有什麼我應該做的不同/以一種不太複雜的方式?

回答

0

要驗證,我建議看看JSONSchema工具。例如,我使用軟件包tv4作爲驗證程序,但也有很多類似的。首先,創建對象的模式:在你的路線

const tv4 = require('tv4'); 

const schema = { 
    type: object, 
    properties: { 
    name: string, 
    phone: string 
    }, 
    required: ['name'] 
}; 

然後,你做:

app.post('/someroute', (req, res, next) => { 
    if (!tv4.validate(req.body, schema)) 
    return next(new Error('not valid input')); 
    // do some cool stuff here 
    res.end(); 
}); 

快遞處理錯誤基本上是增加一箇中間件功能作爲最後的一個,並與另外PARAMS:

// add middleware 
app.use(bodyParser.json()) 

// add custom middleware 
app.use(function(req, res, next) { 
    // some cool stuff 
    next(); 
});  

// add routes 
app.get('/',() => {}) 

// error handler always last 
// Pay attention to additional `err` param 
app.use(function (err, req, res, next) { 
    if (err) { 
    // log error, whatever handling logic 
    } 
    else next(); 
}); 
0

更結構化的方式將有一個單獨的錯誤配置文件,並使用中間件這樣的程序是更好地進行結構拋出錯誤

error.json

"err":[ 
    "errorLog501":{ 
    "status":501, 
    "message":"request is invalid" 
    } 
] 

`

var errCodes = require('./error.json') 
var errMiddleware = function(req, res, next) { 
    if (req.body.hello) { 
    // some cool stuff 
    res.json(errCodes.errorLog501) 
    } else { 
    next(); 
    } 
} 

app.use(errMiddleware); //everytime a request happens the middleware called 

這是非常重要的是通過狀態碼在JSON響應,使得前端可以顯示適當的錯誤消息,並且用戶能夠知道應用程序的狀態