我正在研究 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']
};
然后在你的 route ,你会:
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();
});
express 中的错误处理基本上是添加一个中间件函数作为最后一个函数,并带有附加参数:
// 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();
});
关于javascript - 表达错误处理模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44241203/