Bird
Raised Fist0
Vueframework~20 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of using try...catch blocks in Vue HTTP calls?
easy
A. To handle errors when the HTTP request fails or returns an error
B. To speed up the HTTP request
C. To style the HTTP response data
D. To automatically retry the HTTP request

Solution

  1. Step 1: Understand the role of try...catch

    The try...catch block is used to catch errors that happen during code execution, such as network failures or exceptions.
  2. Step 2: Apply to HTTP calls in Vue

    When making HTTP calls, errors like failed requests or server errors can occur. Using try...catch helps catch these errors and handle them gracefully.
  3. Final Answer:

    To handle errors when the HTTP request fails or returns an error -> Option A
  4. Quick Check:

    Error handling = To handle errors when the HTTP request fails or returns an error [OK]
Hint: Use try...catch to catch HTTP errors in Vue calls [OK]
Common Mistakes:
  • Thinking try...catch speeds up requests
  • Using try...catch to style data
  • Assuming try...catch retries requests automatically
2. Which of the following is the correct syntax to check if an HTTP response was successful in Vue?
easy
A. if (response.status === 200) { ... }
B. if (response.success) { ... }
C. if (response.error) { ... }
D. if (response.ok) { ... }

Solution

  1. Step 1: Identify the standard property for success

    The response.ok property is a boolean that is true if the HTTP status code is in the 200-299 range, indicating success.
  2. Step 2: Compare options

    if (response.status === 200) { ... } checks for exactly 200, which is valid but less flexible. if (response.ok) { ... } uses response.ok, which is the recommended and clearer way. Options C and D are not valid properties.
  3. Final Answer:

    if (response.ok) { ... } -> Option D
  4. Quick Check:

    Check response.ok for success = if (response.ok) { ... } [OK]
Hint: Use response.ok to check HTTP success easily [OK]
Common Mistakes:
  • Checking response.error which does not exist
  • Checking response.success which is invalid
  • Only checking for status 200, missing other success codes
3. Consider this Vue code snippet:
<pre>async function fetchData() { try { const response = await fetch('https://api.example.com/data'); if (!response.ok) { throw new Error('Network response was not ok'); } const data = await response.json(); return data; } catch (error) { return 'Fetch failed'; } } What will fetchData() return if the server responds with status 404?
medium
A. The JSON data from the response
B. 'Fetch failed'
C. undefined
D. An unhandled error

Solution

  1. Step 1: Analyze response status handling

    The code checks response.ok. For status 404, response.ok is false, so it throws an error.
  2. Step 2: Understand catch block behavior

    The thrown error is caught by the catch block, which returns the string 'Fetch failed'.
  3. Final Answer:

    'Fetch failed' -> Option B
  4. Quick Check:

    404 triggers catch, returns 'Fetch failed' = 'Fetch failed' [OK]
Hint: Non-ok response triggers catch block return [OK]
Common Mistakes:
  • Assuming JSON data is returned on 404
  • Expecting undefined instead of catch return
  • Thinking error is unhandled and crashes
4. Identify the error in this Vue HTTP call code:
async function getUser() {
  try {
    const response = await fetch('/user');
    if (response.ok) {
      const user = response.json();
      return user;
    }
  } catch (e) {
    console.error(e);
  }
}
medium
A. Missing await before response.json() causing a Promise to be returned
B. Incorrect use of try...catch block
C. Using response.ok instead of response.status
D. No error, code is correct

Solution

  1. Step 1: Check response.json() usage

    The response.json() method returns a Promise, so it must be awaited to get the actual data.
  2. Step 2: Identify missing await

    The code returns response.json() without await, so it returns a Promise instead of user data.
  3. Final Answer:

    Missing await before response.json() causing a Promise to be returned -> Option A
  4. Quick Check:

    Always await response.json() to get data [OK]
Hint: Always await response.json() to get actual data [OK]
Common Mistakes:
  • Forgetting to await response.json()
  • Thinking response.ok is incorrect usage
  • Assuming try...catch is wrongly used
5. You want to show a user-friendly error message in your Vue app when an HTTP call fails. Which approach best combines error handling and accessibility?
hard
A. Log errors to console only without user notification
B. Ignore errors and reload the page automatically
C. Use try...catch to catch errors, set an error message in state, and display it with aria-live="polite" for screen readers
D. Show a popup alert without any ARIA attributes

Solution

  1. Step 1: Combine error handling with user feedback

    Using try...catch allows catching errors. Setting an error message in Vue state lets the UI update to inform the user.
  2. Step 2: Ensure accessibility with ARIA

    Using aria-live="polite" on the error message container ensures screen readers announce the message politely, improving accessibility.
  3. Final Answer:

    Use try...catch to catch errors, set an error message in state, and display it with aria-live="polite" for screen readers -> Option C
  4. Quick Check:

    Error handling + aria-live = Use try...catch to catch errors, set an error message in state, and display it with aria-live="polite" for screen readers [OK]
Hint: Use aria-live with error messages for accessibility [OK]
Common Mistakes:
  • Ignoring errors or not showing messages
  • Using alerts without ARIA support
  • Logging errors only without user feedback
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard