Handling errors with promises in JavaScript

Tram Ho

If you are a JS programmer, Promise must be too familiar. How do you normally handle it when it returns an error? In this article, let’s learn about it.

1. Error handling with .catch

Assuming there is a segment like this, you have handled enough for both the success and failure of the promise (when the promise is rejected or an error occurs).

myFunc() is not actually a function. This is the part that caused the error. Since you already have the error handling snippet, of course, you will get a log that prints the normal error like this.

And now, let’s try a little change. Let’s position the error line differently, in the then () of the promise like this.

And at this point, the processing for printing your error message has not been triggered anymore, you get the result like this.

Simply understood, because the part you are using to handle errors (error) => {} only catches the cases where the Promise returns errors. In this case the Promise is returned, then it has another piece of code that causes the error that leads to the promise being rejected. So now what to do if I want to handle it? Remember try...catch ? OK, let’s apply. You just need to fix it

The code below executes the promise and let’s understand .catch means there will be an implicit try...catch around it.

When we throw an error in .then, the promise will be rejected, thus jumping to the nearest error handling. The error here is not necessarily an explicitly rejected error, it may be a random error in the handler.

In all 3 cases 1.1, 1.2, and 1.3, errors are handled and printed out to the user.

So always remember. catch() when using promises.

With consecutive series of promises

.catch doesn’t always have to include a .then . It may appear after one or more .then

So if you have a string of promises, how do you handle them while doing them, something goes wrong.

The simplest way is to catch all the errors in the last .catch() in the promise string. This way, if any promises return reject (possibly due to network error or invalid json or whatever), the runtime will jump to the nearest error handling and .catch will trigger them.

2. Throw the bug back

As mentioned .catch at the end of string is similar to try..catch . We can have multiple .then and then use a single .catch at the end to handle the error in all of them. With try ... catch , we can parse the error and re-throw them if it hasn’t been handled yet, so is the promise.

If you throw an error in the .catch , it is routed to the next nearest error handler. And if you handle them and end up normally (with no more errors), it will continue to jump to the next successful handler, here is .then()

Here .catch has been normally ended. So the next .then will continue to be called.

Another example is with .catch() . The handler (*) catches the errors but cannot handle them (in this example it only handles the URIError form), so it throws the error again:

The executable will jump from first .catch (*) to .catch (**) which is next closest handler.

3. Unhandled rejections

What if an error occurs but is not handled. Suppose, you forgot to add .catch to the end of the string like below:

In the event of an error, the promise will be rejected, the execution will go to the closest rejection processing. But it’s not here, so the bug is “stuck”, there’s no code handling it leading to the program crashing and standing there. JavaScript tracks such rejection and generates a global error in that case. You will see a red error message in the console.

To handle them, in the browser, we can catch such errors using unhandledrejection :

This way, if the error occurs and the .catch , you can still notify the user of the error, or you can report the problem to the server.

4. Error in setTimeout

What do you think about this example? .catch catch this error?

And the answer is NO

As mentioned above, an implicit try... catch will work. That try-catch is synchronous. (You can read more here ) So with exceptions occurring in “scheduled” code (such as setTimeout , setInterval ) it will not be possible. To handle this, you can try...catch inside the setTimeout callback

summary

  • .catch handles errors in promises: when calling reject (), or when an error is thrown during processing.
  • Put the .catch in the exact place where you want to handle the error and know how to handle them. When processing we should either parse the error types (using custom error classes) or throw them back.
  • In any case, we should have unhandledrejection (for browsers, and similar environments) to track for unresolved errors and to notify the user (or server) about them, hence, our app. we will avoid crashes.

This article is over, thank you for watching.

Reference: https://javascript.info/promise-error-handling

Share the news now

Source : Viblo