There's single api application like this:
const express = require('express')
const app = express()
const router = require('express').Router()
...
route.post('/dogs', (req, res, next) => {
const dog = new Dog() // it defined in real app
dog.validate() // error happens here
.then(() => {
return res.status(201)
})
// [1]
})
...
app.use('/api/v1', router)
app.use(notFoundErrorHandler)
app.use(globalErrorHandler)
function notFoundErrorHandler (req, res, next) {
res.status(404)
res.send({error: 'Not found'})
}
function globalErrorHandler (err, req, res, next) {
if (err) {
res.status(err.status || 500)
res.json({error: err.message || err})
}
}
If there's validation error it won't pass to the globalErrorHandler
, but catching and rethrowing error solves the problem [1]:
.catch(err => { return next(err) })
Does this behaviour is normal for mongoose with not complete Promise implimentation, or it could be implimentated in another way?
It doesn't raise error when using other methods like save
, find
, etc.