FelixRe_
FelixRe_

Reputation: 195

Returning error from promise in vuex store action

I'm trying to set up a login action using Parser which returns an error if the authentification fails. Then I want to catch the errror and return it to the component where I display the error. However I always get an unhandled promise rejection.

I already tried different methods of rejecting or returning the error with no success. reject(error) (recommended here Returning Promises from Vuex actions) return reject(error) return Promise.reject(error) return Promise.reject(new Error(error)) or simply return error

my actions:

actions: {
      login(vuexContext, authData) {
        console.log(authData.email)
        Parse.User.logIn(authData.email, authData.password)
          .then(user => {
            vuexContext.commit('SET_USER', user)
          })
          .catch(error => {
            console.error('Actions login - Error: ' + error)
            reject(error)
          })
      }

my submit method:

onSubmit() {
      this.$store
        .dispatch('login', {
          email: this.formData.email,
          password: this.formData.password
        })
        .then(() => {
          // ..
        })
        .catch(error => {
          console.log('Catching' + error)
          if (error.code == 101) {
            this.errorMsg = 'Email oder Passwort falsch'
          } else {
            this.errorMsg =
              'Entschuldigung, hier ist etwas schief gelaufen... Fehler: ' +
              error.message
          }
          this.showError = true
          this.$router.push('/sessions/new')
        })
    }

I would expect that the catch block in the onSubmit method catches the error .

Upvotes: 2

Views: 2895

Answers (1)

Gowri
Gowri

Reputation: 394

you have to wrap the function return as a new promise.

actions: {
    login(vuexContext, authData) {
      return new Promise((resolve, reject) => {
        console.log(authData.email)
        Parse.User.logIn(authData.email, authData.password)
          .then(user => {
            vuexContext.commit('SET_USER', user)
            resolve()
          })
          .catch(error => {
            console.error('Actions login - Error: ' + error)
            reject(error)
          })
      })
    }
  }

Upvotes: 3

Related Questions