Join egghead, unlock knowledge.

Want more egghead? It's 45% off for a limited time only!

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock All Content for 45% Off

Already subscribed? Sign In

Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    Catch Errors when Data Fails to Load with Vue.js and RxJS

    John LindquistJohn Lindquist

    Services going down is a part of life, so every app needs to gracefully handle what happens when things aren't working as expected. When errors do occur, RxJS enables you to switch over to another stream of your choosing to load any alternative data you'd like to display.

    vueVue.js
    ^2.0.0
    rxjsRxJS
    ^5.0.0
    javascriptJavaScript
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    Instructor: 00:00 now we'll break our URL and when I click, our data will fail to load. You'll see errors in the console. The way we usually handle this is by .catching the error. This will give us an error and will want to switch over to an observable.

    00:18 The observable that we'll create is going to be an observable of an object that has a name of "Failed," and maybe a frowny face for good measure. We'll hit Save here, clear out console, click, and you can see that it properly failed. My image service also captured the failure to load an unnamed image.

    00:39 Now the cool thing about this is if this fails to load, we can switch over to a different request entirely. I can do a create loader, and then we'll load the other person and make sure and fix the URL. Put the G there, and two will be C-3PO. We'll hit Save there, clear out the console, click, and you'll see that we gracefully handled the error and made a separate request over to loading C-3PO.

    01:07 If I fix this by fixing the URL when hitting Save, then going back and clicking, it'll load Luke. Inside of this catch, simply return an observable that gives us an object with a name on it and an image on it, too, if you wanted. Then, you can gracefully handle any errors that may come your way...

    Discuss

    Discuss