Axios-module: Unable to catch error in fetch style request

Created on 30 Jan 2018  路  8Comments  路  Source: nuxt-community/axios-module

  async handsomeRequest ({ commit, dispatch }, params) {
    try {
      await this.$axios.$post('payment/', qs.stringify(params))
      console.log('Processed!')
    } catch (e) {
      console.log('I am a fat bug')
      console.log(e)
    }

For the vuex action above I'm unable to catch the status 400 error. I have also tried using .then().catch() like below:

 async handsomeRequest ({ commit, dispatch }, params) {
  await this.$axios.$post('payment/', qs.stringify(params))
    .then(res => {
      console.log('success:', res)
    })
    .catch(err => {
      console.log('error', err.response)
    })
}

This question is available on Nuxt.js community (#c75)

Most helpful comment

You should thrown an error in error handle to fix it.
Create plugin for add handlers

// ~/plugins/axios.js
export default function ({$axios, app, store}) {
  $axios.onError(error => {
    console.table(error);
    throw error.response;
  })
})

and add it in nuxt.confix.js.

So after that you will able to handle error in fetch style and simple then/catch

All 8 comments

Do you confirm using non $ prefixed methods it works?

  async handsomeRequest ({ commit, dispatch }, params) {
    try {
      await this.$axios.post('payment/', qs.stringify(params))
      console.log('Processed!')
    } catch (e) {
      console.log('I am a fat bug')
      console.log(e)
    }

I have tried without fetch, it seems to not able to catch error as well. The error response in Chrome Network Browser displays correctly.

2018-01-31_04 32 22_athena_ss

  makePayment ({ commit, dispatch }, params) {
    startLoading(dispatch, 'make payment')
    try {
      const res = this.$axios
        .post('payment/', qs.stringify(params))
      console.log(res)
    } catch (err) {
      Promise.reject(err)
    }
  },

I have the followings axios module config:

  axios: {
    baseURL: 'http://localhost:5000/api',
    credentials: true,
    debug: false,
    init (axios, ctx) {
      axios.defaults.headers.post['Content-Type'] =
        'application/x-www-form-urlencoded'
    },
    requestInterceptor: (config, { store }) => {
      if (store.state.auth.accessToken) {
        config.headers.common['Authorization'] = `Bearer ${
          store.state.auth.accessToken
        }`
      }
      return config
    },
    errorHandler (error, { store, redirect }) {
      if (error.response.status === 401) {
        console.log('expired token, going after /refresh')
        store.dispatch('auth/logout').then(() => {
          redirect('/users/login')
        })
      }
    }
  },

@bin4ryio The above configuration seems for 4.x. Please upgrade and also be sure to read both new Docs and Upgrde Guide. In 5.x release, default error handler is removed so your issues should be resolved.

Thanks for the prompt reply. Now I'm having issue configuring axios request to my backend localhost:5000 instead.

  axios: {
    baseURL: 'http://localhost:5000',
    credentials: true,
    debug: true,
    prefix: '/api',
    proxy: true
  }

I have tried key:value of the followings:

baseURL: 'http://localhost:5000/api'
proxy: false

It seems to keep sending requests to :3000 (nuxt) even if it says the following:

nuxt:build Rebuilding the app... +1ms
nuxt:axios BaseURL: http://localhost:5000 (Browser: /api) +31s

If you don't need proxy, maybe this would be enough:

  axios: {
    baseURL: 'http://localhost:5000/api/',
    credentials: true
  }

Thank you so much @pi0. Now I'm able to do proper promise .then().catch().

I had the same problem (not catching exceptions from axios) and it turned out the exceptions were being caught after all.
However, the code for handling them was buggy and raised other errors, which were muted by another try/catch block.
Hope this helps someone 馃槀

You should thrown an error in error handle to fix it.
Create plugin for add handlers

// ~/plugins/axios.js
export default function ({$axios, app, store}) {
  $axios.onError(error => {
    console.table(error);
    throw error.response;
  })
})

and add it in nuxt.confix.js.

So after that you will able to handle error in fetch style and simple then/catch

Was this page helpful?
0 / 5 - 0 ratings