ReactJS Hook error handeling doesn't catch errors

80 views Asked by At

I am trying to catch a 404 error I receive for some of my API calls.

I am using the matrix API and need to get room names from their id's, which is working. Some of them don't have names which returns a 404 error I am trying to catch. Unfortunately this dosn't work and I don't understand where I'm going wrong. The code itself exectues, but it still throws 404's in the console.

const JoinedRooms = () => {
  const [answer, setAnswer] = useState([]);
  const [isError, setIsError] = useState(false);

  const getAnswer = async () => {
    const res = await fetch(`https://example.com/_matrix/client/r0/joined_rooms`, {
      headers: {
        "Authorization": `Bearer ${localStorage.getItem('mx_access_token')}`
      }
    });

    const answer = await res.json();

    const getNames = await Promise.all(answer.joined_rooms.map(async (roomId) => {
      setIsError(false);
      const res = await fetch(`https://example.com/_matrix/client/r0/rooms/${roomId}/state/m.room.name`, {
        headers: {
          "Authorization": `Bearer ${localStorage.getItem('mx_access_token')}`
        }
      });
      try {
        const roomName = await res.json();
        return roomName.name;
      } catch (error) {
        setIsError(true);
      }
    }));
    setAnswer(getNames);
  }

  useEffect(() => {
    getAnswer();
  }, []);

  return answer;
}

export default JoinedRooms;
1

There are 1 answers

2
dwosk On BEST ANSWER

A 404 status code will not throw an error, so your try...catch block won't catch it. Try getting the 404 directly from the res object returned.

      const res = await fetch(`https://example.com/_matrix/client/r0/rooms/${roomId}/state/m.room.name`, {
        headers: {
          "Authorization": `Bearer ${localStorage.getItem('mx_access_token')}`
        }
      });
      if (res.status === 404) {
        // handle error
      }