I have an existing Node Express Application and want to improve the error handling better. My current route endpoint definition is like below,
app.get('/example/getActiveId', async (req, res, next) => {
// Some code to fetch some details from request and do some validations
try {
const result = await api.getActiveId(id);
res.json({ success: true, result }); // I am getting this response in all the time.
} catch (err) {
console.log('getActiveId', err)
console.error(err);
res.json({ success: false });
}
});
Also, I defined error middleware at the last of all the route paths.
// error handler middleware
app.use((error, req, res, next) => {
console.log('in Error middleware')
console.error(error.stack);
res.status(500).send(error.message || 'Something Broke!');
})
My definition of getActiveId
is as below.
exports.getActiveId = id => axiosInstance
.get('/example')
.then(({ data }) => data)
.catch(er => er);
The problem in the above getActiveId
definition is every time the catch of the getActiveId
, the execution falls into the try block of the above endpoint definition. I wanted the execution should go into the catch block endpoint definition function. So that I could call next(err)
to call the default express error handling middleware.
So I tried the following mockup code to mimic the same with promise reject.
exports.getActiveId = id => {
const __mockPromise = () => {
return new Promise((resolve, reject) => {
reject('Problem in getActiveId')
})
}
return new Promise((resolve, reject) => {
__mockPromise().then(({ data }) => resolve(data)).catch(er => { console.log('in catch....'); reject(er) })
});
}
I expected the above function will go into the catch block of the end point function definition.
But this time I am getting the following error,
in catch....
(node:32897) UnhandledPromiseRejectionWarning: Problem in getActiveId
(node:32897) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 4)
How can I fix this error and bypass the execution to error middleware?