0
0
Vueframework~20 mins

Error handling in HTTP calls in Vue - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
HTTP Error Handling Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What happens when the HTTP call fails in this Vue component?

Consider this Vue 3 component using fetch inside onMounted. What will the user see if the HTTP request returns a 404 error?

Vue
import { ref, onMounted } from 'vue';

export default {
  setup() {
    const data = ref(null);
    const error = ref(null);

    onMounted(async () => {
      try {
        const response = await fetch('https://api.example.com/data');
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        data.value = await response.json();
      } catch (err) {
        error.value = err.message;
      }
    });

    return { data, error };
  },
  template: `<div>
    <p v-if="error">Error: {{ error }}</p>
    <p v-else-if="data">Data loaded</p>
    <p v-else>Loading...</p>
  </div>`
};
AThe component crashes with an uncaught exception.
BThe component shows 'Error: Network response was not ok'.
CThe component shows 'Loading...' indefinitely.
DThe component shows 'Data loaded' even though the request failed.
Attempts:
2 left
💡 Hint

Think about what happens when response.ok is false and how the error is handled.

📝 Syntax
intermediate
2:00remaining
Which option correctly handles HTTP errors in this Vue 3 fetch example?

Identify the option that properly throws an error when the HTTP response is not successful.

Vue
async function fetchData() {
  const response = await fetch('https://api.example.com/items');
  // Error handling here
  const data = await response.json();
  return data;
}
Aif (!response.ok) throw new Error('Failed to fetch');
Bif (response.status >= 400) console.log('Error');
Cif (response.ok) throw new Error('Error occurred');
Dif (response.status !== 200) return null;
Attempts:
2 left
💡 Hint

Check which condition correctly detects an error and throws an exception.

🔧 Debug
advanced
2:00remaining
Why does this Vue 3 component not show the error message on HTTP failure?

Look at the code below. The HTTP call fails but the error message never appears. What is the cause?

Vue
import { ref, onMounted } from 'vue';

export default {
  setup() {
    const error = ref(null);

    onMounted(async () => {
      try {
        const response = await fetch('https://api.example.com/data');
        if (!response.ok) {
          return;
        }
        const data = await response.json();
      } catch (e) {
        error.value = e.message;
      }
    });

    return { error };
  },
  template: `<div>
    <p v-if="error">Error: {{ error }}</p>
    <p v-else>Loading...</p>
  </div>`
};
AThe error is set but the HTTP failure does not trigger the catch block, so the message is never set.
BThe error is set but the template does not display it because 'error' is not returned from setup.
CThe error is set but the component does not re-render because 'error' is not reactive.
DThe error is set but the component returns before setting the error, so it never updates.
Attempts:
2 left
💡 Hint

Consider when the catch block runs and how errors from HTTP status codes are handled.

state_output
advanced
2:00remaining
What is the value of 'error' after this fetch call in Vue 3?

Given this code snippet, what will be the value of error.value after the fetch call if the server returns a 500 status?

Vue
import { ref } from 'vue';

const error = ref(null);

async function loadData() {
  try {
    const response = await fetch('https://api.example.com/data');
    if (!response.ok) {
      throw new Error(`Error: ${response.status}`);
    }
    const data = await response.json();
  } catch (e) {
    error.value = e.message;
  }
}

await loadData();
Anull
B"Network response was not ok"
C"Error: 500"
D"Error: Internal Server Error"
Attempts:
2 left
💡 Hint

Look at the error message thrown when response.ok is false.

🧠 Conceptual
expert
3:00remaining
Which approach best ensures user-friendly error handling in Vue HTTP calls?

Choose the option that best describes a robust way to handle HTTP errors in Vue components to provide clear feedback to users.

AUse synchronous XMLHttpRequest calls to block UI until data loads, then show data or error.
BIgnore HTTP status codes and always display the fetched data, assuming the server returns valid JSON.
COnly catch network errors and ignore HTTP status errors, showing loading until data arrives.
DThrow errors on bad HTTP status, catch them, set a reactive error message, and display it in the template with fallback UI.
Attempts:
2 left
💡 Hint

Think about how to handle both network and HTTP errors gracefully in a reactive UI.