DEV Community

Bhavesh Mishra
Bhavesh Mishra

Posted on

⚠ error handling🍵 understanding

Hi, I was working with some lambda and even though there were error thrown my sentry was not logging the error and then I knew that something is wrong with my error handling mechanism.

Normally if you throw manual throw new Error or do console.error and your sentry will catch that provided you are not suppressing that error.
Lets me come with some example

rejectFunc = () => Promise.reject('rejected');
testFunc = () => Promise.resolve('1').then(a => console.log('resolved'));
Enter fullscreen mode Exit fullscreen mode

Now if I do testFunc() the expected outcome is resolved which was logged by then block

Image description

Now lets throw some errors by ourself

testFunc = () => Promise.resolve('1')
  .then(a => {
    rejectFunc()
  })
  .catch(() => console.log('rejected'))
Enter fullscreen mode Exit fullscreen mode

What is the outcome you expect?🤔

Should it will run the then block or catch block?

Image description

The catch block statement was not logged but why? there was an error correct as in red block the js engine throw that error Uncaught (in promise) rejected

Lets understand this, in the then block we don't have return hence the final return is undefined which is not an error and catch block didn't run.As the error was not handled by us.

Now lets run that same code again with returning the error

testFunc = () => Promise.resolve('1')
  .then(a => {
    return rejectFunc()
  })
  .catch(() => console.log('rejected'))
Enter fullscreen mode Exit fullscreen mode

Image description

Here you can see the catch block was run also any other error by v8 engine was not thrown as we had handled the error by ourself.

Now lets go with async await(which I prefer over then/catch)

testFunc = () => Promise.resolve('1').then(a => { testVar }).catch(a => console.log(a))

Enter fullscreen mode Exit fullscreen mode

I have a function with testVar declared which has no reference now if I run the code I will have

Image description
But If I use simple try catch with empty catch block which specify we are handling the error

Image description
No error was thrown the code specify we have handled the error even through we are not doing anything in catch block hence in these scenario the error will never reach to sentry.

Lets try one more thing
Now inside catch block I have console error with what ever the error I have

Image description

Now you can see the error was thrown and sentry will catch this one

So we should always handle the error properly always using console.log in catch block or not returning the promise and expecting the catch block is there which will handle the error for us is not going to help.

That's the end of this blog.

Please feel free to add something if I was wrong somewhere and also lets discuss in comment section if we have

Top comments (0)