javascriptvue.jsasync-components

Capture network error on async component Vue 2


I'm spending quite a lot of time just to understand how I can handle network errors in the Async component in Vue v2.

so I want to display an error message if something wrong happens during API call.

here's the example of the code: codesandbox

Vue:

<child-component
  v-if="showChild"
  message="I am the child component."
  loadingMessage="Looking for child component..."
  errorMessage="Child component not available."
></child-component>
mounted() {
    var that = this;
    fetch("https://api.github.com/users/dasdasdasdasdasdas") //wrong url dasd... just for testing
      .then(function (res) {
        return res.json();
      })
      .then(function (data) {
        console.log(data);
        that.showChild = true;
      })
      .catch(function (err) {
        console.log(err);
      });
},

Solution

  • an async component's error state is only enabled if there is a rejection returned by the import promise, i.e. only when this line fails:

    import(/* webpackChunkName: "childComp" */ "@/components/ChildComponent.vue")
    

    This import is not tied to your fetch call in any way. If you want to display an error message if your fetch fails, you can just use a boolean flag variable that controls a different v-if error element/component:

    <child-component
          v-if="showChild"
          message="I am the child component."
          loadingMessage="Looking for child component..."
          errorMessage="Child component not available."
    ></child-component>
    <div v-if="showError">Error message here</div>
    
    data() {
      return {
        showChild: false,
        showError: false
      };
    },
    
    mounted() {
      var that = this;
      fetch("https://api.github.com/users/dasdasdasdasdasdas")
        .then(function (res) {
          return res.json();
        })
        .then(function (data) {
          console.log(data);
          that.showChild = true;
        })
        .catch(function (err) {
          console.log(err);
          that.showError = true;
        });
    },
    

    By the way, your example URL https://api.github.com/users/dasdasdasdasdasdas does not return a network error. 4xx and 5xx error codes can actually be valid responses. If you want to enter your catch block you need to use a completely fake hostname, e.g. fake.url.com/api, and/or specifically handle 404s in your then() block:

    .then(function (res) {
      if (res.ok) {
        return res.json();
      } else {
        throw new Error('to the catch block');
      }
    })