Vue 3 Global Error Handler

Vue 3 Global Error Handler

Vue 3 Global Error Handler

Vue 3 provides a global error handler that catches errors thrown in component lifecycle hooks, event handlers, and setup().

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

const app = createApp(App)

app.config.errorHandler = (err, instance, info) => {
  // err     — the error object
  // instance — the component instance that threw
  // info    — Vue-specific info (e.g. "setup function")

  console.error(`[Vue Error] ${info}:`, err)

  // Send to monitoring service
  // Sentry.captureException(err, { extra: { info } })
}

app.config.warnHandler = (msg, instance, trace) => {
  console.warn(`[Vue Warn] ${msg}\n${trace}`)
}

app.mount('#app')
<!-- ErrorBoundary.vue — catch errors in a subtree -->
<script setup>
import { onErrorCaptured, ref } from 'vue'

const error = ref(null)

onErrorCaptured((err) => {
  error.value = err.message
  return false // prevent propagation to parent
})
</script>

<template>
  <div v-if="error" class="error">Something went wrong: {{ error }}</div>
  <slot v-else />
</template>
All Comments