简体   繁体   English

React Native - 未处理的 Promise 拒绝 - 在哪里捕获错误?

[英]React Native - Unhandlled Promise Rejection - where to catch the error?

i'm getting 'Possible Unhandled Promise Rejection' warning in my react native app.我在我的反应原生应用程序中收到“可能未处理的 Promise 拒绝”警告。 I understand its because im not catching the error at all, but I just dont know where to do it in my function which is:我理解它,因为我根本没有发现错误,但我只是不知道在我的 function 中在哪里做:

return async dispatch => {
        const response = await fetch(url);

        const resData = await response.json();
        const pastResults = resData.past;
        const nextResults = resData.next;
        const lastResult = resData.last;

        const loadedResults = [];
        for (let r = 0; r < 11; r++){
            loadedResults.push(
                new FakeResult(
                  r,
                  pastResults[r].drawingDate.substring(0,10),
                  pastResults[r].nr,
                  pastResults[r].numbers
                )
              );
        }

        dispatch({type: SET_RESULTS, results: loadedResults, next: nextResults, last: lastResult});
    };

Thanks a lot for your help!非常感谢你的帮助!

try/catch around the await statements ( or any statement potentially returning rejected promises ) try/catch await语句(或任何可能返回被拒绝的承诺的语句)

return async dispatch => {
    try {
        const response = await fetch(url);
        const resData = await response.json();
    } catch(err) {
      // do something with err or ignore(?)
    }

    const pastResults = resData.past;
    const nextResults = resData.next;
    const lastResult = resData.last;

    const loadedResults = [];
    for (let r = 0; r < 11; r++){
        loadedResults.push(
            new FakeResult(
              r,
              pastResults[r].drawingDate.substring(0,10),
              pastResults[r].nr,
              pastResults[r].numbers
            )
          );
    }

    dispatch({type: SET_RESULTS, results: loadedResults, next: nextResults, last: lastResult});
};

NOTE: fetch only returns a rejected promise for network failures, not error responses.注意: fetch仅针对网络故障返回被拒绝的 promise,而不是错误响应。

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

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