简体   繁体   English

无需 thunk 的 redux-promise-middleware 错误处理

[英]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'.我们正在使用 redux-promise-middleware 并且在解决错误处理方面遇到一些困难,所有作为 400 代码返回的错误都被处理为“已完成”。 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.由于我们没有使用 redux-thunk,我特别询问您将如何处理从承诺返回的 400 错误。

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.任何帮助是极大的赞赏。

First of all you don't need to set payload to {promise: promise} Just put the promise directly Try this for first首先你不需要设置payload为{promise: promise}直接把promise放上去试试这个

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现在答案是:首先,您需要检查 API.doSomething(object) 是否抛出错误或在 400 响应代码的情况下返回 Promise.reject()

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 Promise 不知道你代码里面发生了什么,为了得到DO_SOMETHING_REJECTED就是让API.doSomething(object)抛出 400

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM