[Vuejs]-What is the best way to handle Http Exception error messages in vuejs?

3๐Ÿ‘

โœ…

I usually make a js/mixins/Errors.js file with all my error methods and then just include the mixin in my vue files.

export const errorsMixin = {
methods: {
    errorClass(item, sm = false) {
        return { 'form-control': true, 'form-control-sm': sm, 'is-invalid': this.validationErrors.hasOwnProperty(item) }
    },
    buttonClass() {
        return ['btn', 'btn-primary', this.saving ? 'disabled' : '']
    },
    handleError(error) {
        this.saving = false
        if (error.response.status == 422) {
            this.validationErrors = error.response.data.errors;
        } else {
            alert(error.response.data.message)
        }
    },
}
}

In each vue file:

import { errorsMixin } from '../../mixins/Errors.js'
export default {
    mixins: [errorsMixin],

    ......
    .catch((err) => {
        this.handleError(err)
    })

}
๐Ÿ‘คJoeGalind

Leave a comment