Home » vue » Catching errors in computed properties in Vue

Catching errors in computed properties in Vue

Posted by: admin November 26, 2021 Leave a comment


In VueJS I have a vuex store getter which may throw an error of type ErrorOne or ErrorTwo.

// myGetter.js
export class ErrorOne extends Error {}
export class ErrorTwo extends Error {}

export default () => {
    if (...) {
        throw new ErrorOne()
    if (...) {
        throw new ErrorTwo()
    return ...

And in a computed property in my Vue component I am using this getter but I want to handle these errors in a try catch block.

// MyComponent.vue
import { ErrorOne, ErrorTwo } from '.../myGetter'

export default {
    data() {
        return {
            errorOne: false,
            errorTwo: false
    computed: {
        myGetterComputed() {
            try {
                const value = this.$store.getters['.../myGetter']
                this.errorOne = false            // Unexpected side effect
                this.errorTwo = false            // Unexpected side effect
                return value
            } catch (err) {
                switch (err.constructor) {
                    case ErrorOne:
                        this.errorOne = true     // Unexpected side effect
                    case ErrorTwo:
                        this.errorTwo = true     // Unexpected side effect


But eslint tells me [eslint] Unexpected side effect in "myComputedGetter" computed property. [vue/no-side-effects-in-computed-properties].

What is the correct way to handle errors in Vue computed properties in my use case?

Should I move myGetterComputed to data and use a watch method to handle updates?


If I am going straight to answer your question I can tell you that eslint is using this rule to warn you about an unintended side effect. As per the eslint-plugin-vue docs

It is considered a very bad practice to introduce side effects inside computed properties. It makes the code not predictable and hard to understand.

Basically what we need to remember is that computed properties are meant to be used when there’s heavy logic associated to how we treat data inside templates. So you shouldn’t be updating any properties/data inside a computed property logic.

I would like to help you further if you provide a more detailed example of what you’re trying yo achieve