π οΈ Vue API Error Handling β Manage HTTP Failures Gracefully (2025 Guide)
π§² Introduction β Why Handle API Errors in Vue?
When building Vue applications that rely on APIs, handling HTTP errors is crucial. Network failures, invalid inputs, expired tokens, or server issues can break the user experience. Implementing structured error handling ensures stability, better debugging, and clear user feedback.
π― In this guide, youβll learn:
- How to catch errors using Axios or Fetch in Vue
- Best practices for handling HTTP status codes
- How to show error messages in the UI
- Centralized and component-level strategies
π« Common API Error Scenarios
Scenario | Example Status |
---|---|
Invalid request | 400 Bad Request |
Unauthorized/expired token | 401 Unauthorized |
Resource not found | 404 Not Found |
Server crash or unavailability | 500+ |
π Axios Error Handling Structure
Axios errors have a structured error.response
object that contains details:
axios.get('/api/posts')
.catch(error => {
if (error.response) {
console.log(error.response.status); // HTTP status code
console.log(error.response.data); // API error message
} else {
console.log('Network Error', error.message);
}
});
π§± Vue Component Error Example (Axios)
<template>
<div>
<p v-if="error" class="error">{{ error }}</p>
<ul v-else>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
items: [],
error: null
};
},
created() {
axios.get('/api/items')
.then(res => this.items = res.data)
.catch(err => {
if (err.response && err.response.status === 404) {
this.error = 'Items not found.';
} else {
this.error = 'Something went wrong.';
}
});
}
};
</script>
<style>
.error {
color: red;
}
</style>
π§ Display errors clearly, fallback gracefully.
𧬠Handling Errors with Fetch API
Fetch doesnβt throw errors on HTTP status codes. You must manually check the response:
fetch('/api/items')
.then(res => {
if (!res.ok) throw new Error(`Error ${res.status}`);
return res.json();
})
.then(data => this.items = data)
.catch(err => this.error = err.message);
π§° Real-World Pattern β Error, Loading, Data States
data() {
return {
items: [],
error: null,
loading: false
};
},
created() {
this.loading = true;
axios.get('/api/items')
.then(res => this.items = res.data)
.catch(err => this.error = 'Failed to load items')
.finally(() => this.loading = false);
}
β
Use conditional rendering (v-if
) to display loaders and messages.
π§ Global Axios Error Interceptors
For token expiry, API downtime, etc.
axios.interceptors.response.use(
res => res,
err => {
if (err.response.status === 401) {
alert('Session expired. Redirecting to login.');
window.location.href = '/login';
}
return Promise.reject(err);
}
);
π¨ Displaying Errors in UI
Method | Example |
---|---|
v-if="error" | Conditionally render an error block |
Modal/Toast | Use component libraries like Vuetify or Toastify |
Console logs (dev) | Helpful during development only |
β οΈ Best Practices for Vue API Error Handling
Practice | Why It’s Important |
---|---|
Always handle .catch() | Prevents uncaught promise rejections |
Check error.response in Axios | It contains actual API feedback |
Use finally() for cleanup | Show/hide loaders regardless of success |
Avoid exposing server errors to users | Display friendly messages only |
π Summary β Recap & Next Steps
Vue API error handling keeps your app robust and user-friendly. Whether you use Axios or Fetch, structured handling ensures that failures donβt become fatal.
π Key Takeaways:
- Use
.catch()
and check status codes - Fetch needs manual status handling
- Track loading and error state with
data()
- Centralize token-based or auth errors using interceptors
βοΈ Real-World Relevance:
Vital for production apps with forms, dynamic content, login flows, and API integrations.
β FAQ Section
β How do I catch Axios API errors in Vue?
β
Use .catch(err)
and check err.response.status
.
β Why is fetch()
not throwing errors for bad status?
β
It only throws on network failures. Use if (!res.ok)
to catch HTTP errors.
β How can I display error messages to users in Vue?
β
Store error in data()
and show it with v-if
, or use modal/toast libraries.
β What if I want to handle errors globally in Vue?
β Use Axios interceptors to handle specific statuses like 401 or 500 across the app.
β Should I expose full API error messages to users?
β No. Log them for devs, but show friendly messages to users.
Share Now :