Error handling in JavaScript (ES6) generators

Max Stoiber
InstructorMax Stoiber
Share this video with your friends

Social Share Links

Send Tweet

One can throw an error in a generator from the outside with it.throw(). Since all the code inside of a generator is synchronous, we can use the standard try/catch method of handling errors!

[00:00] We see here is a simple generator, which gets a word from the outside, in the case Max, and then console.logs hello and whatever the word is that we passed in. If we run this, you will see that expected it will log Hello Max.

[00:14] The thing about this generator is that it looks like synchronous code, but because we have his yield key word with which we can pause and resume generators at arbitrary points, there's arbitrary amount of things that can happen while the generator is paused.

[00:31] In between the first .next call and the second .next call, there can be a thousand things we could do. We could fetch data, we could do all sorts of asynchronous stuff before resuming our generator again. This means while this code looks synchronous, is actually fully asynchronous.

[00:47] Now the thing is, if something goes wrong in one of the thousands of things we could do between the first .next call and the second .next call, how can we tell that to our generator? How can we tell our generator, hey, something went wrong?

[01:01] What we can do is we can use the throw word. We can type hello.throw to throw an error inside the generator wherever it's paused right now, so in our case, at this yield keyword. If we run this, you will see that it will just say, hey, an error was thrown at this yield key word.

[01:19] Now it's kind of bad how this ends the whole process, our whole app would crash if any error was thrown inside a generator, which is not what we want. The nice thing about generators is that they look synchronous.

[01:32] Synchronous things just work, in our case we can just use a standard try-catch block to catch an error. There's nothing fancy or asynchronous going on, it's just a standard try-catch block, then we can console.log error, right?

[01:47] If we run this code you would see, hey, it actually logs error because an error happens, because we did hello.throw. Now, if we tried to log the error that we get passed, you will see that it will just say undefined. Why? Because we didn't pass anything to the hello.throw call.

[02:03] This is similar to next, except it throws an error, so we can pass an error message in her, saying for example, something went wrong. If we try running this again, it will log error, something went wrong.