Error Handling and Global Interceptors
Handle request errors and configure Axios interceptors.
Error Handling and Global Interceptors is a free Vue Academy lesson on CoddyKit — lesson 3 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Vue Academy learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Requests Can Fail
Networks drop, servers return errors, and tokens expire. Robust apps anticipate failure and respond gracefully instead of crashing or leaving the user staring at a spinner forever.
try/catch Around Requests
Wrap awaited requests in try/catch to capture errors. Axios throws when the server responds with a 4xx or 5xx status.
async fetchPosts() {
try {
const res = await api.get("/posts")
this.posts = res.data
} catch (err) {
console.error(err)
}
}Inspecting the Error
An Axios error carries useful details. error.response exists when the server replied, while its absence usually means a network or timeout failure.
catch (err) {
if (err.response) {
console.log(err.response.status)
console.log(err.response.data)
} else {
console.log("Network error")
}
}Tracking an Error State
Store an error message in reactive state so the template can display it to the user.
data() {
return { posts: [], loading: false, error: null }
}Setting the Error
Reset the error before each request, then populate it in the catch block.
async fetchPosts() {
this.loading = true
this.error = null
try {
this.posts = (await api.get("/posts")).data
} catch (err) {
this.error = "Could not load posts. Please try again."
} finally {
this.loading = false
}
}Displaying Error Messages
Show the error in the template so users understand what went wrong and what to do next.
<template>
<p v-if="loading">Loading...</p>
<p v-else-if="error" class="error">{{ error }}</p>
<ul v-else>
<li v-for="p in posts" :key="p.id">{{ p.title }}</li>
</ul>
</template>What Are Interceptors?
Axios interceptors let you run code on every request or response automatically. They are perfect for cross-cutting concerns like attaching tokens or handling errors in one central place.
Request Interceptors
A request interceptor runs before each request leaves. Use it to attach an auth header globally.
api.interceptors.request.use(config => {
const token = localStorage.getItem("token")
if (token) {
config.headers.Authorization = "Bearer " + token
}
return config
})Response Interceptors
A response interceptor runs after each response arrives. It takes two callbacks: one for success and one for errors.
api.interceptors.response.use(
response => response,
error => {
if (error.response && error.response.status === 401) {
// redirect to login
}
return Promise.reject(error)
}
)Global Error Handling
Centralizing error logic in a response interceptor means individual components stay clean. Common cases like 401 (logout) or 500 (show a toast) live in one place.
api.interceptors.response.use(
res => res,
error => {
const status = error.response ? error.response.status : null
if (status === 401) logout()
if (status >= 500) showToast("Server error, try later")
return Promise.reject(error)
}
)Simple Retry Logic
For flaky networks you can retry a failed request a limited number of times before giving up.
async function getWithRetry(url, retries = 2) {
try {
return await api.get(url)
} catch (err) {
if (retries > 0) {
return getWithRetry(url, retries - 1)
}
throw err
}
}Quick Check
Test your knowledge of error handling and interceptors.
Recap
Wrap requests in try/catch, surface a friendly error message in the UI, and inspect error.response to distinguish server vs network failures. Interceptors centralize concerns: request interceptors attach tokens, response interceptors handle global errors, and a small retry helper adds resilience. Next you will optimize app performance.
Frequently asked questions
Is the “Error Handling and Global Interceptors” lesson free?
Yes — the full text of “Error Handling and Global Interceptors” is free to read here on the web, and the Vue Academy course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Vue Academy course, upgrade to CoddyKit PRO.
What will I learn in “Error Handling and Global Interceptors”?
Handle request errors and configure Axios interceptors. You practise Vue Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Vue Academy?
No prior experience is required. Vue Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 3, so you can start here or from the beginning and move at your own pace.
How long does the “Error Handling and Global Interceptors” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Vue Academy lesson?
Yes. Every Vue Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- HTTP Requests with Axios
- Lifecycle Hooks and Data Fetching
- Error Handling and Global Interceptors