bubbaspaarx
bubbaspaarx

Reputation: 726

redux-promise-middleware error handling without thunk

We are using redux-promise-middleware and having some difficulty working out what to do about error handling, all errors returned as 400 codes are just handled as 'FULFILLED'. I get that this is probably the correct behaviour but surely there is a way to catch an error in a promise in this setup. As we are not using redux-thunk, I am specifically asking how you would handle say a 400 error being returned from a promise.

our setup is very basic but I'm sure we should be able to

const export doSomething = object => {
 const promise = API.doSomething(object)
 return {
  type: "DO_SOMETHING",
  payload: {promise: promise}
 }
}

reducer

export default (state = initialstate, action) {
 switch(action.type){
  case "DO_SOMETHING_FULFILLED":
   return action.payload
  case "DO_SOMETHING_REJECTED":
   return console.log(action.payload)
  default:
   return initialstate
}

any help is greatly appreciated.

Upvotes: 0

Views: 179

Answers (1)

Rami Loiferman
Rami Loiferman

Reputation: 912

First of all you don't need to set payload to {promise: promise} Just put the promise directly Try this for first

export const doSomething = object => {
 return {
  type: "DO_SOMETHING",
  payload: API.doSomething(object)
 }
}

This is just a little decoration suggestion(not obligated)

export const doSomething = object => ({
   type: "DO_SOMETHING",
   payload: API.doSomething(object)
})

Now the answer: First of all you need check if API.doSomething(object) throws an Error Or returns Promise.reject() on case of 400 respond code

If it doesn't you need to make it throw

if(res.code === 400) {
  throw new Error()
}

// Or just use a library like axios 

Promise doesn't know what happened inside you code, in order to get to DO_SOMETHING_REJECTED Is to make the API.doSomething(object) throw in 400

Upvotes: 1

Related Questions