1

I am wondering if I can still use .catch() within an async function to catch the error instead of using a try-catch block.

The following code is from my project using MongoDB and Express:

router.get('/communities', EnsureAuthenticated, async (req, res) =>{ 

//Look up the user in the db + populate the community field 
const userInfo = await User_DB
.findOne({ _id:req.user._id, })
.populate('communities') 
.lean()
.catch(err => {
console.log(err)
 res.status(500)
.json({
 msg: 'DB: Error Fetching User Info',
});

// rest of the functions that take userInfo as the input

});

When using try-catch all variables will be limited to within the scope of that try-catch block.

If I need to use the userInfo as the input for other functions down the line I'll have to put everything within that try-catch block which doesn't look clean and can be confusing. Because you don't know which function does the error belongs to if there is any.

Is my understanding correct?

I apologize for the formatting. I'm doing this on my phone.

Algo7
  • 2,122
  • 1
  • 8
  • 19
  • "*I am wondering if I can still use `.catch()` within an async function*" - yes of course, it's still a promise after all. Doesn't it work? – Bergi Jul 15 '20 at 21:30
  • 1
    "*When using `try`/`catch` all variables will be limited to within the scope of the `try` block.*" - yes, but usually that's not an issue. There would be only one block encompassing all your calls and handling all the errors. In contrast, your `.catch()` call just causes `userInfo` to become `undefined`, but won't actually break execution or anything. This is probably not what you wanted. Rather do re-throw an error from the `.catch()` handler with the specific error message that you want. – Bergi Jul 15 '20 at 21:33
  • It's just that I havent seen anyone writting code in this way. It's either the .then .catch or the async-await + try catch. The code hasn't produce any error so far. vscode and eslint seems to be ok with the syntax. Just wondering. – Algo7 Jul 15 '20 at 21:36
  • [I do](https://stackoverflow.com/a/44664037/1048572)! :-) – Bergi Jul 15 '20 at 21:36
  • Thank you for your prompt reply. When you said that `.catch()` will actually cause the `userInfo` to become undefined. That's the case when the error happens right? Furthermore, how do I know which error is from which function when I put everything in the try-catch block? I mean of course I can just read the stack trace but let's say I want to customize the error message for each function and return that to the user. How would that work? Because when I use the try-catch to handle errors there is usually only one function within. Thanks :) – Algo7 Jul 15 '20 at 21:41
  • See also [this answer](https://stackoverflow.com/a/60046785/1048572) – Bergi Jul 15 '20 at 21:42
  • 1
    "*When you said that `.catch()` will actually cause the userInfo to become undefined. That's the case when the error happens right?*" - yes. "*how do I know which error is from which function*" - yes, that's where `.catch(err => { throw … })` (or even `.then(…, …)`) comes into play – Bergi Jul 15 '20 at 21:44
  • So I will still need to wrap it in a try-catch so that the error thrown within `.catch()` can be caught right? If I don't, the code will continues it's execution and the `userInfo` will become undefined. – Algo7 Jul 15 '20 at 21:48
  • 1
    The `userInfo` will not become `undefined` if you rethrow an error – Bergi Jul 15 '20 at 22:00
  • What will it become then? The error which has been rethrown? – Algo7 Jul 15 '20 at 22:01
  • If the error is rethrown, then `await` evaluates to an exception and `userInfo` becomes nothing at all, as the control flow will go the the `catch` clause of the surrounding `try`. – Bergi Jul 16 '20 at 12:31
  • have done the above for almost 30 API endpoints already. Thank you for diverting me from this path which might ultimately crash. Could you please organize the above and put it as an answer so I can mark this questions as resolved? – Algo7 Jul 16 '20 at 15:22

1 Answers1

0

You can also make a central error handler, you can find an example here

Sgh
  • 234
  • 1
  • 6