Plugin for globally handling form errors

Learn how to handle errors globally.

To handle Vueform submit error messages globally in our application, we can create a plugin:

js
// vueform.config.js

import { defineConfig } from '@vueform/vueform'

const errorHandlerPlugin = {
  apply: 'Vueform',
  setup(props, context, component) {
    // Subscribe to Vueform's error event for each form
    component.on('error', (error, details, form$) => {
      form$.messageBag.clear() // clear message bag

      switch (details.type) {
        // Error occured while preparing elements (no submit happened)
        case 'prepare':
          form$.messageBag.append('Could not prepare form')
          break

        // Error occured because response status is outside of 2xx
        case 'submit':
          form$.messageBag.append('The form could not be processed')
          break

        // Request cancelled (no response object)
        case 'cancel':
          form$.messageBag.append('Form submission cancelled')
          break

        // Some other errors happened (no response object)
        case 'other':
          form$.messageBag.append('Failed to submit the form')
          break
      }
    })

    return {
      ...component,
    }
  }
}

export default defineConfig({
  plugins: [
    errorHandlerPlugin,
  ]
})
  
👋 Hire Vueform team for form customizations and developmentLearn more