ReactJS Hook 错误处理不会捕获错误

ReactJS Hook error handeling doesn't catch errors

我正在尝试捕捉我在某些 API 调用中收到的 404 错误。

我正在使用矩阵 API 并且需要从他们的 id 中获取房间名称,这是有效的。其中一些没有名称,returns 我试图捕捉到 404 错误。不幸的是,这不起作用,我不明白我哪里出错了。代码本身会执行,但它仍然会在控制台中抛出 404。

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;

404 状态代码不会 throw 错误,因此您的 try...catch 块不会捕获它。尝试直接从返回的 res 对象获取 404。

      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
      }