Currently, I am exploring the use of Express for developing a basic JSON API. However, I have concerns about how to effectively manage input parameter validation and error handling in my project. Errors can occur during both the validation process and when accessing the database. Here's the current structure:
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))
})
The validation process is defined as follows:
const validate = function(q) {
return new Promise(function(resolve, reject) {
if (q.someParameter) {
if (somethingWrong(q.someParameter)) {
reject(new Error("Something wrong!"))
}
}
resolve()
})
}
Do you think this approach is logical? Are there any suggestions on how I could improve or simplify it?