Rob Walker
Rob Walker

Reputation: 47452

Handle Vue render errors locally

I am using Vue (server side rendered) with mjml to generate emails.

So I have something (overly simplified) like:

<mjml><mj-body>Hello {{ User.Name }}</mj-body></mjml>

If the model doesn't define User then Vue throws an error and the whole output is lost.

What I want to the output to be along the lines:

<mjml><mj-body>Hello <error>'User' is undefined</error></mj-body></mjml>

I have implemented Vue.config.errorHandler but that just tells me about the error -- there is no rendered output.

Anyway to implement the equivalent of an error handler around each variable substitution?

Upvotes: 0

Views: 1253

Answers (1)

ittus
ittus

Reputation: 22393

If you are using Vue version >= 2.5, you can use errorCaptured to create an ErrorBoundary

const ErrorBoundary = {
  name: 'ErrorBoundary',
  data: () => ({
    error: false,
    msg: ''
  }),
  errorCaptured (err, vm, info) {
    this.error = true
    this.msg = `${err.stack}\n\nfound in ${info} of component`
  },
  render (h) {
    return this.error 
      ? h('pre', this.msg) 
      : this.$slots.default[0]
  }
}

and use this in your component

  <error-boundary>
    <mjml><mj-body>Hello {{ User.Name }}</mj-body></mjml>
  </error-boundary>

If the application has any javascript error, it will be displayed on UI

enter image description here

Example on codepen

If you want to have more user-friendly error, you can customize ErrorBoundary to have fallback to another component. You can find out in this tutorial

Another good example of using errorHandler

Upvotes: 2

Related Questions