react-async-hook icon indicating copy to clipboard operation
react-async-hook copied to clipboard

Fix unhandled promise rejection propagation

Open pmomot opened this issue 3 years ago • 2 comments

In executeAsyncOperation the promise rejection scenario is not properly handled. It captures the error, saves it in state, but then it propagates further and causes exceptions in the codebase. I suggest to change the implementation to this

return promise
      .then((result) => {
        if (shouldHandlePromise(promise)) {
          AsyncState.setResult(result);
        }
        normalizedOptions.onSuccess(result, {
          isCurrent: () => CurrentPromise.is(promise),
        });
      })
      .catch((error) => {
        if (shouldHandlePromise(promise)) {
          AsyncState.setError(error);
        }
        normalizedOptions.onError(error, {
          isCurrent: () => CurrentPromise.is(promise),
        });
      });

instead of

promise.then(() => {}, () => {});

pmomot avatar Jul 13 '22 11:07 pmomot

I have the same probleme. I have to try cath my requests even if I use onError to handle error

damienromito avatar Sep 23 '22 14:09 damienromito

const resultRef = useRef();
const { result } = useAsync(async( $params, $condition ){
   if($condition){
       return await yourPromiseFunction($params).then((response)=>{
       //handle your response
       if( response is error ){
           const error: Error = {
          name: "Error Occurred",
          message: "Error",
          stack: "no stack"
          console.error(error.name, res.ResultMessage);
          throw error;
        }
       }
     })
   }
},
[params, condition],
{
    setLoading: (state) =>  ({
      ...state
      result: resultRef.current ?? state.result,
      loading: true
  }),
    setResult: (result, asyncState) => ({
    ...asyncState,
    result:
      result === undefined ? resultRef .current : result,
    loading: false
  }),
    onSuccess: ( result , { isCurrent })=>{
      if (isCurrent()) {
        resultRef.current = result ?? resultRef.current;
        //do the rest
      }
    },
    onError:()=>{}
}
)

pig800509 avatar Jun 06 '23 03:06 pig800509