[英]Express error handling pattern
我正在研究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()
})
}
這有意義嗎? 有什么我應該做的不同/以一種不那么令人費解的方式?
為了驗證,我建議看一下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();
});
快遞中的錯誤處理基本上是關於添加中間件函數作為最后一個,並使用其他參數:
// 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();
});
更結構化的方法是使用單獨的錯誤配置文件並使用中間件拋出該錯誤,這樣您的應用程序的結構更好
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響應中傳遞狀態代碼非常重要,這樣前端可以顯示相應的錯誤消息,用戶可以知道應用程序的狀態
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.