Map an Error to a Broadcaster Value in React

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 4 years ago

Errors happen, so let's catch them and map them. This lesson walks through mapping an error to a different value to display to the user so they know what's happening when something goes wrong.

Congrats on finishing Section 06: Bringing the Pattern into React!πŸŽ‰πŸŽ‰

πŸ‘‰ CLICK HERE to continue to the next section, Building Light Search Box. πŸ‘ˆ

Instructor: [0:00] Let's go ahead and handle this error in a graceful way. With promises, you do that with catch, so we can catch the error. For right now, just pass it down to the listener. I'll hit Save. Now, we caught the error and sent that down and it's logging the error out. With this error, I can write an operator to map it to something else.

[0:24] I'll write mapError as the name of our operator. Let us call our mapping function transform, and broadcaster, then listener. I can return the broadcaster, push the value through. If the value is an instance of error, then, I can, into the listener, transform that value. Otherwise, just do the default behavior.

[0:55] It's only going to do this if that value shows up as an error. Let's go ahead and use this around our broadcaster. We'll wrap this and say mapError. We'll take the error, and then just return something else. For now, I'll just say "Whoopsie," hit Save here. You can see, we get a Whoopsie out of here. I could do something like doing the error.message, hit Save, "The user aborted the request."

[1:24] If I wanted to target this login name right here, I could just map this to an object. That object is our profile, and it has a login on it of error.message. That would look like this, an object with a login. It has the message on it. If this didn't error, meaning we don't cancel, the object comes through fine. If it does error, then we can just map it to something else.

egghead
egghead
~ 6 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today