Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Tools
Online Compiler JSON Formatter Regex Tester CSS Unit Converter Color Picker
Compiler Tools

Vue Error Handling onErrorCaptured Global Handler: Causes, Fixes, Examples & Interview Tips

Error Handling Strategies

Vue provides several mechanisms to handle errors gracefully - from component-level error boundaries to global error handlers. Good error handling prevents blank screens and gives users meaningful feedback.

onErrorCaptured, Global Handler, Async Errors
<!-- ErrorBoundary.vue - catches errors from child components -->
<template>
  <div>
    <div v-if="error" class="error-boundary">
      <h3>Something went wrong</h3>
      <p>{{ error.message }}</p>
      <details v-if="isDev">
        <summary>Error details</summary>
        <pre>{{ errorInfo }}</pre>
      </details>
      <button @click="reset">Try Again</button>
    </div>
    <slot v-else />
  </div>
</template>

<script setup>
import { ref, onErrorCaptured } from 'vue'

const error = ref(null)
const errorInfo = ref(null)
const isDev = import.meta.env.DEV

// Catches errors from ALL descendant components
onErrorCaptured((err, instance, info) => {
  error.value = err
  errorInfo.value = info

  // Log to error tracking service
  console.error('Caught error:', err, 'in:', info)
  // logToSentry(err, { component: instance?.$options.name, info })

  return false  // prevent error from propagating further
})

function reset() {
  error.value = null
  errorInfo.value = null
}
</script>

<!-- Usage: -->
<!-- <ErrorBoundary> -->
<!--   <UserProfile :userId="userId" /> -->
<!-- </ErrorBoundary> -->
// main.js - global error handlers

import { createApp } from 'vue'
import App from './App.vue'

const app = createApp(App)

// Global error handler - catches all unhandled errors
app.config.errorHandler = (err, instance, info) => {
    console.error('Global error:', err)
    console.error('Component:', instance?.$options.name)
    console.error('Info:', info)

    // Send to error tracking (Sentry, Bugsnag, etc.)
    // Sentry.captureException(err, { extra: { info } })

    // Show user-friendly notification
    // toast.error('An unexpected error occurred')
}

// Global warning handler (development only)
app.config.warnHandler = (msg, instance, trace) => {
    console.warn('Vue warning:', msg)
    console.warn('Trace:', trace)
}

// Handle unhandled promise rejections
window.addEventListener('unhandledrejection', (event) => {
    console.error('Unhandled promise rejection:', event.reason)
    event.preventDefault()  // prevent default browser error
})

// Handle global JS errors
window.addEventListener('error', (event) => {
    console.error('Global JS error:', event.error)
})

app.mount('#app')
<!-- Async error handling patterns -->
<template>
  <div>
    <div v-if="state.loading">Loading...</div>
    <div v-else-if="state.error" class="error">
      <p>{{ state.error }}</p>
      <button @click="fetchData">Retry</button>
    </div>
    <div v-else>
      <pre>{{ state.data }}</pre>
    </div>
  </div>
</template>

<script setup>
import { reactive, onMounted } from 'vue'

const state = reactive({
  data: null,
  loading: false,
  error: null,
})

async function fetchData() {
  state.loading = true
  state.error = null

  try {
    const res = await fetch('/api/data')

    if (!res.ok) {
      // HTTP errors (4xx, 5xx) don't throw - check manually
      throw new Error(`Server error: ${res.status} ${res.statusText}`)
    }

    state.data = await res.json()
  } catch (err) {
    if (err instanceof TypeError) {
      // Network error (no internet, CORS, etc.)
      state.error = 'Network error. Check your connection.'
    } else if (err.name === 'AbortError') {
      // Request was cancelled
      state.error = null  // not really an error
    } else {
      state.error = err.message || 'An unexpected error occurred'
    }
    console.error('Fetch error:', err)
  } finally {
    state.loading = false
  }
}

onMounted(fetchData)
</script>

Deep Dive: Error Handling in Real Projects

Understanding Error Handling is not just about syntax. In production applications, this topic directly affects maintainability, debugging speed, and team collaboration. Focus on readability, small reusable patterns, and predictable state flow when implementing Error Handling.

A practical approach is to first implement the simplest working version, then refactor into reusable pieces (components/composables/stores) only when duplication appears. This helps keep your Vue codebase clean while avoiding over-engineering.

Common Mistakes to Avoid

  • Mixing too many responsibilities in one component instead of separating logic by concern.
  • Skipping meaningful naming for variables, emits, and component props.
  • Ignoring edge cases like empty data, loading states, and error handling.
  • Optimizing too early before measuring real bottlenecks in browser devtools.
  • Not creating small test scenarios to validate behavior after each change.

Mini Practice Checklist

  1. Build a small demo focused only on Error Handling.
  2. Add one edge case (empty/loading/error) and handle it cleanly.
  3. Refactor repeated logic into a reusable function/composable.
  4. Add clear comments only where logic is non-obvious.
  5. Verify behavior with manual testing and Vue Devtools.
Key Takeaways
  • This chapter on Error Handling focuses on practical Vue 3 patterns used in real projects.
  • Prefer the Composition API with script setup for cleaner and more scalable component logic.
  • Keep components focused and move reusable logic into composables when complexity grows.
  • Use Vue Devtools to inspect component state, props, emits, and performance during development.
  • Write small experiments for each concept before applying it in production code.
  • After finishing this chapter, continue to the next related topic in the Vue roadmap.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.