I have a helper function that hits an API and fetches a page by ID. It uses async/await and I am trying to handle errors with try catch.
To test the error handling I am purposefully giving it an ID that does not exist.
Here is the method:
const findPage = async (req, res, pageId) => {
let document
try {
let response = await getByID(pageId)
if (!response) throw Error('No Response')
return document
} catch (error) {
console.log(error) // I can see the error is being thrown.. I am purposefuly giving it an id that does not exist
return error
}
}
It does indeed throw an error like I expect. However, I am calling the function in another part of the app using an express Route.
Router.route('/page/:id').get(async (req, res) => {
let results
try {
results = await findPage(req, res, req.params.id) // This Function Returns an error
// Yet we still get results
res.json({results, msg: 'WHY?'})
} catch (error) {
res.send(error)
}
})
In the same Router file, I have attempted to add some specific middleware to this Router as well, but as there is no error, it is never triggered.
Router.use((err, req, res, next) => {
if (err) {
console.log('holy error')
} else {
console.log('no error')
}
next(err)
})
How can the express API call return results, and not the error, when the function it is calling itself returns an error?
You are catching the error in
findPage()which means the error won't propagate up the call stack. You are just returning the error like a normal value, which will end up in the variableresultsin yourRoutesfunction. If you want to deal with the error in both places you need tothrowit again infindPage():If you don't want to deal with it on both places,
catchit in the function that's responsible for handling errors: