1

I have one function which checks for user authorization

export const authUser = (rideId, action) => {
  return (dispatch, getState) => {
    const postData = {
      consumer: "Rapi",
      classId: rideId,
      action: action,
    };
    return Api.post(
      '/api/xx/yy/auth',
      postData,
    )
    .then((response) => {
      const authorized = response && response.authorized === true;
      if (authorized) {
        console.log("User is authorized");
        return true;
      } else {
        console.warn("User is NOT authorized");
        return false;
      }
    })
    .catch((error) => {
      console.error(" Authorization failed:", error);
      return false;
    });
  };
};

If user is authorized to access this particular ride in that case we are getting this below response from API:

{ "authorized": true }

If that particular RideId is not available or he is not authorized to access that ride we are getting below response from API:

{
    "message": "Ride not found. rideId: RD23435OPSMSK76772",
    "errorCode": "60000",
    "timestamp": "2025-07-02T08:34:57.241+00:00"
}

As of now I am displaying a common message for user not authorized and ride not found error. But I want to display this particular message which we are receiving from API response. When ride Id is not found I am getting above response and catch block is executing. We are getting response in ride not found case, so then .then block should get executed.

1
  • Perhaps the response status of the request is one that makes Api.post to throw an error. Commented Jul 2 at 14:23

2 Answers 2

0

As of now I am displaying a common message for user not authorized and ride not found error. But I want to display this particular message which we are receiving from API response.

If you would like to display the specific "Ride not found. rideId: RD23435OPSMSK76772" in the UI then it needs to be returned from your thunk action back to the caller so it can be handled in the UI and rendered.

When ride Id is not found I am getting above response and catch block is executing. We are getting response in ride not found case, so then .then block should get executed.

This is normal and to be expected with API error responses. Handle the error in the catch block accordingly.

Suggestions

  • Update authUser to return a resolved Promise, e.g. true|false, if the user is authorized, otherwise return a rejected Promise with the error. This means returning the caught error from the catch block by re-throwing it.

    export const authUser = (rideId, action) => async () => {
      const postData = {
        consumer: "Rapi",
        classId: rideId,
        action,
      };
    
      try {
        const response = await Api.post(
          '/api/xx/yy/auth',
          postData,
        );
        const result = await response.json();
        console.info("Authorization result", result);
        // Resolve with result value
        return result.authorized;
      } catch(error) {
        console.error("Authorization failed:", error);
        // Re-throw error to reject Promise with error
        throw error;
      }
    };
    
  • Update callees to await the dispatched Thunk action and handle promise rejections and capture the error message to be rendered later in the UI.

    const [errorMessage, setErrorMessage] = React.useState(null);
    
    ...
    
    const callback = async (....) => {
      try {
        setErrorMessage(null);
    
        // Wait for Thunk action to settle.
        const authorized = await dispatch(authUser(rideId, action));
        // Dispatched action resolved, auth action was successful,
        // do something with auth result.
        if (authorized) {
          console.log("User is authorized");
        } else {
          console.warn("User is NOT authorized");
        }
      } catch(e) {
        // Dispatch action rejected, handle error.
        setErrorMessage(e.message); // i.e. "Ride not found. rideId: RD23435OPSMSK76772"
      }
    }
    
    ...
    
    return (
      ...
      {/* Display any current error messages. */}
      {errorMessage && (
        <div>Error: {errorMessage}</div>
      )}
      ...
    );
    
Sign up to request clarification or add additional context in comments.

Comments

-2

For displaying the specific error message, instead of a generic unauthorized message, you will need to manage the API response properly in your .then() block rather than depending on the .catch() for this case.

Why?

Your API returns a JSON error response with status 200 or a non-error HTTP status) even when the ride is not found, so .then() is executed, not .catch(). The .catch() runs only on network errors or non-2xx HTTP status code.

How to fix?

Modify your .then() to check if the response keeps an error message to handle it accordingly, for example:

export const authUser = (rideId, action) => {
  return (dispatch, getState) => {
    const postData = {
      consumer: "Rapi",
      classId: rideId,
      action: action,
    };
    return Api.post('/api/xx/yy/auth', postData)
      .then((response) => {
        if (response.errorCode) {
          // Handle error response from API
          console.warn("Error:", response.message);
          return Promise.reject(new Error(response.message)); // to trigger catch if needed
        }
        const authorized = response.authorized === true;
        if (authorized) {
          console.log("User is authorized");
          return true;
        } else {
          console.warn("User is NOT authorized");
          return false;
        }
      })
      .catch((error) => {
        console.error("Authorization failed:", error.message || error);
        return false;
      });
  };
};

2 Comments

Did you wrtite this with the help of ChatGPT?
What do you think this function does?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.