Handle Errors when Data Fetching in Vue with Axios

Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 2 years ago

We'll handle any fetching errors using the .catch() property of the axios promise. We'll also add some indication for our users to let them know that we had a problem.

We'll do this by setting an error data property to true when we have an error and conditionally render an error message to the user.

Instructor: [0:00] How are we going to handle if the API fails or there's an error in the fetch? Axios is promise-based, so we can use the .catch() function to be able to do something with our error.

[0:13] If there is an error, we will .catch() the error. For the moment, let's console.log() the error, and let's break the URL. In our console, we see it's a "404 Not Found," so we are getting an error, but for our user, there's nothing to tell them that something's gone wrong. There are a number of ways that we could approach telling our user something's wrong.

[0:38] We could add an error Boolean, and if there is an error rather than console logging, we can say, this.error = true, and then in our UI where this ticket types components being rendered, so here, we could add a heading say "History," that only shows if there's an error and say, "Sorry, we're having trouble getting the ticket types. Try again later."

[1:16] If there's a correct data fetch, we get the ticket types. If there's not, we get an helpful error message for our user.

egghead
egghead
~ 5 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