如何处理Firebase存储异常

kqlmhetl  于 2023-01-21  发布在  其他
关注(0)|答案(3)|浏览(132)

我的应用程序从Firebase存储中获取图像。如果没有图像,我希望能够处理错误。但我似乎无法让它工作。
我试过用"试抓"来包围。
我试过这个

Future<dynamic> getImage(int index){
      return FirebaseStorage.instance.ref().child(widget.snap[index].data['英文品名']+".jpg").getDownloadURL().catchError((onError){
        print(onError);
      }); 
 }

还有这个

Future<dynamic> getImage(int index){
   var imageStream;
   try {
       imageStream = FirebaseStorage.instance.ref().child(widget.snap[index].data['英文品名']+".jpg").getDownloadURL();    
   } catch (e) {
     print(e);
   }
   return imageStream;
 }

但我总是得到未处理的异常错误和我的应用程序崩溃。

E/StorageException(11819): StorageException has occurred.
E/StorageException(11819): Object does not exist at location.
E/StorageException(11819):  Code: -13010 HttpResult: 404
E/StorageException(11819): StorageException has occurred.
E/StorageException(11819): Object does not exist at location.
E/StorageException(11819):  Code: -13010 HttpResult: 404
E/StorageException(11819): {  "error": {    "code": 404,    "message": "Not Found.  Could not get object",    "status": "GET_OBJECT"  }}
E/StorageException(11819): java.io.IOException: {  "error": {    "code": 404,    "message": "Not Found.  Could not get object",    "status": "GET_OBJECT"  }}

如何处理此异常?Image of exception in VS Code

ktecyv1j

ktecyv1j1#

上传文件将采取不同的时间根据图像的大小。所以最有可能你的错误是因为错误的组合异步和等待。这段代码为我工作。

Future<String> uploadSingleImage(File file) async {
    //Set File Name
    String fileName = DateTime.now().millisecondsSinceEpoch.toString() +
        AuthRepository.getUser().uid +
        '.jpg';
    
    //Create Reference
    Reference reference = FirebaseStorage.instance
        .ref()
        .child('Single Post Images')
        .child(fileName);

    //Now We have to check status of UploadTask
    UploadTask uploadTask = reference.putFile(file);
    
    String url;
    await uploadTask.whenComplete(() async {
      url = await uploadTask.snapshot.ref.getDownloadURL();
    });
    print('before return');
    return url;
  }
mdfafbf1

mdfafbf12#

抛出该错误是因为您尝试在尚未创建下载URL的时候访问它。
你可以像下面的例子那样把你的上传代码 Package 在if语句中,这样你就可以保证上传任务成功完成。

if(storageRef
        .child(folderName)
        .putFile(fileName).isSuccessful)
      {
        url = await storage.child("folderName").child(fileName).getDownloadURL();
      }
g52tjvyc

g52tjvyc3#

您可以检查对象是否存在,如下所示:

import 'package:firebase_core/firebase_core.dart' as firebase_core;

    final islandRef=FirebaseStorage.instance
              .ref()
              .child(widget.snap[index].data['英文品名']+".jpg");
            try {
        // returns Future<String> getDownloadURL()
              final var url= await islandRef.getDownloadURL();
              .getDownloadURL()
            } on firebase_core.FirebaseException catch(error) {
              // if the Object does not exists
              if (error.code == 'object-not-found')) {
                  //DO something
              }
            
            }

相关问题