When your app talks to the internet, things can go wrong. Error handling helps your app stay friendly and clear when problems happen.
Error handling in HTTP calls in Vue
<script setup> import { ref } from 'vue' const error = ref(null) async function fetchData() { error.value = null try { const response = await fetch('https://api.example.com/data') if (!response.ok) { throw new Error(`Error: ${response.status}`) } const data = await response.json() // use data here } catch (err) { error.value = err.message } } </script>
Use try...catch to catch errors from HTTP calls.
Check response.ok to handle HTTP errors like 404 or 500.
<script setup> import { ref } from 'vue' const error = ref(null) async function loadUser() { error.value = null try { const res = await fetch('https://api.example.com/user') if (!res.ok) throw new Error('User not found') const user = await res.json() } catch (e) { error.value = e.message } } </script>
<script setup> import { ref } from 'vue' const error = ref(null) async function getPosts() { error.value = null try { const response = await fetch('https://api.example.com/posts') if (!response.ok) { throw new Error(`Failed to load posts: ${response.status}`) } const posts = await response.json() } catch (error) { error.value = error.message } } </script>
This Vue component has a button to load data from a public API. If the fetch fails, it shows a clear error message in red. If it succeeds, it shows the data nicely formatted. The error message uses ARIA roles for accessibility.
<template>
<main>
<button @click="fetchData">Load Data</button>
<p v-if="error" role="alert" aria-live="assertive" style="color: red;">Error: {{ error }}</p>
<pre v-if="data">{{ JSON.stringify(data, null, 2) }}</pre>
</main>
</template>
<script setup>
import { ref } from 'vue'
const data = ref(null)
const error = ref(null)
async function fetchData() {
error.value = null
data.value = null
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1')
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`)
}
data.value = await response.json()
} catch (err) {
error.value = err.message
}
}
</script>Always reset error state before new requests to avoid stale messages.
Use aria-live and role="alert" to announce errors to screen readers.
Network errors and HTTP errors are different; catch both with try...catch and response.ok.
Error handling keeps your app friendly when internet calls fail.
Use try...catch and check response.ok to catch problems.
Show clear messages and use accessibility features for all users.
Practice
try...catch blocks in Vue HTTP calls?Solution
Step 1: Understand the role of
Thetry...catchtry...catchblock is used to catch errors that happen during code execution, such as network failures or exceptions.Step 2: Apply to HTTP calls in Vue
When making HTTP calls, errors like failed requests or server errors can occur. Usingtry...catchhelps catch these errors and handle them gracefully.Final Answer:
To handle errors when the HTTP request fails or returns an error -> Option AQuick Check:
Error handling = To handle errors when the HTTP request fails or returns an error [OK]
- Thinking try...catch speeds up requests
- Using try...catch to style data
- Assuming try...catch retries requests automatically
Solution
Step 1: Identify the standard property for success
Theresponse.okproperty is a boolean that is true if the HTTP status code is in the 200-299 range, indicating success.Step 2: Compare options
if (response.status === 200) { ... } checks for exactly 200, which is valid but less flexible. if (response.ok) { ... } usesresponse.ok, which is the recommended and clearer way. Options C and D are not valid properties.Final Answer:
if (response.ok) { ... } -> Option DQuick Check:
Check response.ok for success = if (response.ok) { ... } [OK]
- Checking response.error which does not exist
- Checking response.success which is invalid
- Only checking for status 200, missing other success codes
<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?Solution
Step 1: Analyze response status handling
The code checksresponse.ok. For status 404,response.okis false, so it throws an error.Step 2: Understand catch block behavior
The thrown error is caught by thecatchblock, which returns the string 'Fetch failed'.Final Answer:
'Fetch failed' -> Option BQuick Check:
404 triggers catch, returns 'Fetch failed' = 'Fetch failed' [OK]
- Assuming JSON data is returned on 404
- Expecting undefined instead of catch return
- Thinking error is unhandled and crashes
async function getUser() {
try {
const response = await fetch('/user');
if (response.ok) {
const user = response.json();
return user;
}
} catch (e) {
console.error(e);
}
}Solution
Step 1: Check response.json() usage
Theresponse.json()method returns a Promise, so it must be awaited to get the actual data.Step 2: Identify missing await
The code returnsresponse.json()withoutawait, so it returns a Promise instead of user data.Final Answer:
Missing await before response.json() causing a Promise to be returned -> Option AQuick Check:
Always await response.json() to get data [OK]
- Forgetting to await response.json()
- Thinking response.ok is incorrect usage
- Assuming try...catch is wrongly used
Solution
Step 1: Combine error handling with user feedback
Usingtry...catchallows catching errors. Setting an error message in Vue state lets the UI update to inform the user.Step 2: Ensure accessibility with ARIA
Usingaria-live="polite"on the error message container ensures screen readers announce the message politely, improving accessibility.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 CQuick Check:
Error handling + aria-live = Use try...catch to catch errors, set an error message in state, and display it witharia-live="polite"for screen readers [OK]
- Ignoring errors or not showing messages
- Using alerts without ARIA support
- Logging errors only without user feedback
Ready to prove it?
Pass the test and this pattern moves unknown
