Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

281
Visualizações
how to handle get error when trying to get non existing data at start in firebase?

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();
    }
  }, []);

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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();
     }, []);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda