Recibo un error GET/404 cuando mi efecto de uso solicita un elemento que no existe al comienzo de la carga de la aplicación, o si el usuario aún no ha configurado ninguna imagen de perfil. Obtuve 2 errores, el bloque catch maneja uno, pero aún recibo un error.
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(); } }, []);Firebase Storage tiene un controlador de errores incorporado. Vea el código de ejemplo a continuación:
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; } }); El código anterior debería manejar el error de Firebase. Si el archivo no existe, habrá un error GET 404 (No encontrado) en la pestaña de su consola/red. Hay una solución para este escenario, puede ejecutar un comando list() o listAll() para asegurarse de que el archivo exista en el directorio antes de ejecutar getDownloadURL() . Vea el código de muestra a continuación para referencia:
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(); }, []);