svrcekmichal / redux-axios-middleware

Redux middleware for fetching data with axios HTTP client
MIT License
920 stars 96 forks source link

Reject (FAIL) action based on response #71

Open gerhardsletten opened 6 years ago

gerhardsletten commented 6 years ago

Have a case where an api do not return the correct error-status with request that fails, so I have added an interceptors in the axios-request

const client = axios.create({
  baseURL: 'https://api.domain.com'
})

client.interceptors.response.use((response) => {
  if (response.data && response.data.status && response.data.status === 'error') {
    return Promise.reject(new Error(response.data.message || 'Request failed'))
  }
  return response
}, (error) => {
  return Promise.reject(error)
})

This works fine with a plain axios, a request that contain a status-fields which is 'error', can be catched in the promise:

client.get('/auth/login', {
  params: {
    username: 'bar',
    passord: 'foo'
  }
}).then((data) => console.log('LOGIN OK', data))
.catch((error) => console.log('LOGIN ERROR', error.message))

With redux-axios-middleware I can get the action to fail with returnRejectedPromiseOnError option in config:

const middleware = [
  axiosMiddleware(client, {
    returnRejectedPromiseOnError: true
  })
]

But I also get a unhandled error in the console (which is not happening with the plain axios-setup)

HTTP Failure in Axios Error: Wrong username or passord.
    at App.js:22
    at tryCallOne (core.js:37)
    at core.js:123
    at JSTimers.js:295
    at _callTimer (JSTimers.js:148)
    at _callImmediatesPass (JSTimers.js:196)
    at Object.callImmediates (JSTimers.js:464)
    at MessageQueue.__callImmediates (MessageQueue.js:282)
    at MessageQueue.js:137
    at MessageQueue.__guard (MessageQueue.js:269)