This lesson is for PRO members.

Unlock this lesson NOW!
Already subscribed? sign in

Error handling in JavaScript (ES6) generators

2:16 JavaScript lesson by

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!

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

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!

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.

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.

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.

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?

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.

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.

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?

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.

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.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?