How to catch StorageException in flutter

Viewed 419

I'm using Firebase storage with flutter. If the upload operation fails for whatever reason (e.g. exceeds size limits set in console), it causes a StorageException.

I want to do something like this:

try {
  final uploadTask = ref.putFile(docFile);
  taskSnapshot = await uploadTask.onComplete;
} on StorageException catch (err) {
  // Do something 
}

But there isn't any StorageException type and I can't find a way to catch any and all exceptions. Any ideas?

2 Answers

You can do something like the following instead.

import 'package:firebase_core/firebase_core.dart' as firebase_core;
try {
  final uploadTask = ref.putFile(docFile);
  taskSnapshot = await uploadTask.onComplete;
} on firebase_core.FirebaseException catch(e) {
     if (e.code == 'permission-denied') {
        /// Real permisssion-denied handling
        print('User does not have permission to upload to this reference.');
    }
    if (e.code == 'the-error-code-printed-to-console') {
        ///the-error-code-printed-to-console handling
        print('printing what you want');
    }

}

This handles errors and checks if it's due to permission. If you are looking for another cause, you can just print the e.code to the console first, copy the code and check if the code copied previously from console is equal to e.code.

try catch doesnt work very well, I solved it like this:

}, onError: (e) {
        debugPrint('Exception::: ==========>>>>>>> ${e.toString()}');
      });

It get it that way

Related