简体   繁体   English

在Redux中处理异步操作错误的最佳实践是什么?

[英]What is the best practice for handling async action errors in redux?

export const saveSomething = (thing = {}) => {
  dispatch({
    type: THING_SAVING,
  });

  return async function (dispatch) {
    try {
      await persistThing(thing);
    } catch (e) {
      dispatch({
        type: THING_SAVE_ERROR,
        error: e,
      });
      throw e;
    }

    dispatch({
      type: THING_SAVED,
      error: e,
    });
  }
}

handleSubmitClick(e) {
  dispatch(saveSomething({ name: e.target.value }))
    .catch(e => {
      // pass
    });
}

So, I'm probably overthinking this, but I'm trying to figure out the best practice here. 因此,我可能对此有过多的思考,但是我正在尝试找出最佳实践。 When my async action has an error, even though I'm dispatching an error, it still feels right to throw it so the promise is rejected in case some components want to key on that. 当我的异步操作发生错误时,即使我正在调度一个错误,也仍然可以将其抛出,因此如果某些组件想要在其上键入内容,则诺言将被拒绝。 But, then that means in order to not have Create-React-App bomb on an unhandled promise rejection, I need to add this dummy catch when I dispatch the action, which IMHO is kinda ugly. 但是,这意味着为了避免在未处理的诺言拒绝中出现Create-React-App炸弹,我需要在分派操作时添加此虚拟捕获,恕我直言,这很丑陋。

What's the best practice here? 这里的最佳做法是什么? Not throw the error? 不会抛出错误? Use the dummy catch? 使用假人? Something else? 还有吗

Edit: The reason I need the dummy catch is because otherwise the app is bombing on me, at least in create-react-app: 编辑:我需要虚拟捕获的原因是因为否则应用程序在我身上轰炸,至少在create-react-app中:

在此处输入图片说明

(the error doesn't 100% match my pseudo code, but you get the point) (错误并非100%与我的伪代码匹配,但您明白了)

In my own projects I would try to manage all the error applications, probably with some generic action dispatcher that could be modified with proper error codes. 在我自己的项目中,我将尝试管理所有错误应用程序,可能使用一些可以用适当的错误代码修改的通用动作分派器。 But as for your example, you might not want to throw the error over, because you are using await in the method that can cause the error. 但就您的示例而言,您可能不想将错误抛出,因为在可能导致错误的方法中使用了await So I would rewrite the code like this: 所以我将这样重写代码:

export const saveSomething = (thing = {}) => {
  dispatch({
    type: THING_SAVING,
  });

  return async function (dispatch) {
    try {
      await persistThing(thing);
      dispatch({
       type: THING_SAVED,
      });
    } catch (e) {
      dispatch({
        type: THING_SAVE_ERROR,
        error: e,
      });
    }
  }
}

If nothing happens and everything goes through the happy path, after the completion of the async call persistThing , the action dispatcher would get executed. 如果什么也没发生,并且一切顺利,那么异步调用persistThing完成后,动作分派器将被执行。 And if persistThing generates an exception, the error action dispatcher would get executed. 并且如果persistThing生成异常,则将执行错误操作分派器。

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

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