Marek
Marek

Reputation: 155

How to refactor catch method

i have a code for error handling that im using in few components, and think a better way would be to write one function that can be used in many places instead of copying the same code everywhere. Belowe my example:

this.fetchDataFromAPI(this.filters)
      .then(() => {})
      .catch(error => {
        if ((!error.body.invalidFields || !Object.keys(error.body.invalidFields).length) && error.body.errorMessage) {
          this.$message({
            message: error.body.errorMessage,
            type: MESSAGES_TYPES.error
          })
        }
        if (error.body.invalidFields && Object.keys(error.body.invalidFields).length) {
          const errors = error.body.invalidFields
          Object.keys(errors).forEach(error => {
            this.errors.push(
              {
                message: errors[error],
                path: [error]
              }
            )
          })
          ValidatorClass.validFormIfBackendErrors(this.errors, this.$refs[this.formName])
        }
      })

How can i refactor this?

Upvotes: 2

Views: 41

Answers (1)

Prime
Prime

Reputation: 2849

You can define error handler as a named function that can be reused.

const errorHandler = error => {
  if ((!error.body.invalidFields || !Object.keys(error.body.invalidFields).length) && error.body.errorMessage) {
    this.$message({
      message: error.body.errorMessage,
      type: MESSAGES_TYPES.error
    })
  }
  if (error.body.invalidFields && Object.keys(error.body.invalidFields).length) {
    const errors = error.body.invalidFields
    Object.keys(errors).forEach(error => {
      this.errors.push(
        {
          message: errors[error],
          path: [error]
        }
      )
    })
    ValidatorClass.validFormIfBackendErrors(this.errors, this.$refs[this.formName])
  }
}

this.fetchDataFromAPI(this.filters)
  .then(() => {})
  .catch(errorHandler)

Upvotes: 2

Related Questions