在 firebase 中尝试在启动时获取不存在的数据时如何处理获取错误?

发布于 2025-01-10 22:40:56 字数 811 浏览 0 评论 0原文

当我的使用效果调用应用程序加载开始时不存在的元素时,或者用户尚未设置任何个人资料图像时,我收到 GET/404 错误。 我遇到了 2 个错误,catch 块处理了一个错误,但我仍然遇到了 1 个错误。

输入图片此处描述

useEffect(() => {
 if (_authContext?.currentUser) {
      const getImg = async () => {
        const storage = getStorage();
        const storageRef = ref(storage, `profiles/${_authContext.currentUser.uid}/profile-image`);
        await getDownloadURL(storageRef)
          .then((url) => {
            if (url) {
              setLoaded(url)
            }
          })
          .catch((err) => console.log(err));
      };
      getImg();
    }
  }, []);

I am getting a GET/404 error when my use effect is calling for an element that doesn't exist at the start of app loading, or if the user has not set any profile image just yet.
I was getting 2 errors the catch block handle one but still I am getting one error.

enter image description here

useEffect(() => {
 if (_authContext?.currentUser) {
      const getImg = async () => {
        const storage = getStorage();
        const storageRef = ref(storage, `profiles/${_authContext.currentUser.uid}/profile-image`);
        await getDownloadURL(storageRef)
          .then((url) => {
            if (url) {
              setLoaded(url)
            }
          })
          .catch((err) => console.log(err));
      };
      getImg();
    }
  }, []);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

调妓 2025-01-17 22:40:56

Firebase 存储具有内置错误处理程序。请参阅下面的示例代码:

import { getStorage, ref, getDownloadURL } from "firebase/storage";

// Create a reference to the file we want to download
const storage = getStorage();
const storageRef = ref(storage, `profiles/${_authContext.currentUser.uid}/profile-image`);

// Get the download URL
getDownloadURL(storageRef)
  .then((url) => {
    if (url) {
      setLoaded(url)
    }
  })
  .catch((error) => {
    // A full list of error codes is available at
    // https://firebase.google.com/docs/storage/web/handle-errors
    switch (error.code) {
      case 'storage/object-not-found':
        // File doesn't exist
        break;
      case 'storage/unauthorized':
        // User doesn't have permission to access the object
        break;
      case 'storage/canceled':
        // User canceled the upload
        break;

      // ...

      case 'storage/unknown':
        // Unknown error occurred, inspect the server response
        break;
    }
  });

上面的代码应该处理来自 Firebase 的错误。如果该文件不存在,您的控制台/网络选项卡中将会出现 GET 404(未找到)错误。对于这种情况有一个解决方法,您可以运行 list( )listAll() 命令,以在运行 getDownloadURL() 之前确保文件是否存在于目录中。请参阅下面的示例代码以供参考:

useEffect(() => {
         const getImg = async () => {
           const storage = getStorage();
           const storageFolderRef = ref(storage, `test/`);
           const imageRef = ref(storage, `test/profile-image.png`);
          // Find all the prefixes and items.
          listAll(storageFolderRef)
            .then((res) => {
              if (res.items.length > 0) {
                getDownloadURL(imageRef)
                .then((url) => {
                  if (url) {
                   setLoaded(url)
                  }
                })
                .catch((error) => {
                 // A full list of error codes is available at
                 // https://firebase.google.com/docs/storage/web/handle-errors
                 switch (error.code) {
                   case 'storage/object-not-found':
                     // File doesn't exist
                     break;
                   case 'storage/unauthorized':
                     // User doesn't have permission to access the object
                     break;
                   case 'storage/canceled':
                     // User canceled the upload
                     break;
             
                   // ...
             
                   case 'storage/unknown':
                     // Unknown error occurred, inspect the server response
                     break;
                 }
                });
              }
            }).catch((error) => {
              console.log(error);
            });
         };
         getImg();
     }, []);

Firebase Storage have built-in error handler. See example code below:

import { getStorage, ref, getDownloadURL } from "firebase/storage";

// Create a reference to the file we want to download
const storage = getStorage();
const storageRef = ref(storage, `profiles/${_authContext.currentUser.uid}/profile-image`);

// Get the download URL
getDownloadURL(storageRef)
  .then((url) => {
    if (url) {
      setLoaded(url)
    }
  })
  .catch((error) => {
    // A full list of error codes is available at
    // https://firebase.google.com/docs/storage/web/handle-errors
    switch (error.code) {
      case 'storage/object-not-found':
        // File doesn't exist
        break;
      case 'storage/unauthorized':
        // User doesn't have permission to access the object
        break;
      case 'storage/canceled':
        // User canceled the upload
        break;

      // ...

      case 'storage/unknown':
        // Unknown error occurred, inspect the server response
        break;
    }
  });

The code above should handle the error from Firebase. If the file doesn’t exist, there’ll be a GET 404 (Not Found) error in your console / network tab. There's a workaround for this scenario, you can run a list() or listAll() command to ensure if the file exist in the directory before running the getDownloadURL(). See sample code below for reference:

useEffect(() => {
         const getImg = async () => {
           const storage = getStorage();
           const storageFolderRef = ref(storage, `test/`);
           const imageRef = ref(storage, `test/profile-image.png`);
          // Find all the prefixes and items.
          listAll(storageFolderRef)
            .then((res) => {
              if (res.items.length > 0) {
                getDownloadURL(imageRef)
                .then((url) => {
                  if (url) {
                   setLoaded(url)
                  }
                })
                .catch((error) => {
                 // A full list of error codes is available at
                 // https://firebase.google.com/docs/storage/web/handle-errors
                 switch (error.code) {
                   case 'storage/object-not-found':
                     // File doesn't exist
                     break;
                   case 'storage/unauthorized':
                     // User doesn't have permission to access the object
                     break;
                   case 'storage/canceled':
                     // User canceled the upload
                     break;
             
                   // ...
             
                   case 'storage/unknown':
                     // Unknown error occurred, inspect the server response
                     break;
                 }
                });
              }
            }).catch((error) => {
              console.log(error);
            });
         };
         getImg();
     }, []);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文