This is the server:
app.use(authMiddleware)app.use(express.json())app.use(CUSTOMERS, customerRouter)app.use(handleError)function startServer() {
So handle error is the last middleware, this is the route code:
The route that creates the user has a validation like this:
const userRouter: Router = Router()userRouter.post('/', validateUser, newUser)
And new user function is this:
async function newUser( request: Request, response: Response, next: NextFunction) { try { const user = await createUser(request.body) return response.status(201).json(user) } catch (err) { console.log('why not!', err)//I can see this log return next(err) }}
When the validator detects invalid post it works and error handler is called:
function validateUser( request: Request, response: Response, next: NextFunction) { const errors = validate(request.body) errors.length ? next(new HttpError(400, 'Invalid user sent', errors)) : next() next()}
But when I sent valid user body but it contains an email that is already in use the createUser will throw and it is caught by the newUser (log shows) but error handler never gets called.
function handleError( error: HttpError, req: Request, response: Response, _next: NextFunction//yes, added next, express is using length for some reason) { console.log('returning json', error)//never see this log on duplicate email return response.status(error.status ?? 500).json({ message: error.message, errors: error.errors, })}