Home > Enterprise >  Flutter - Async file reading exception handling
Flutter - Async file reading exception handling

Time:11-25

I am new to dart/flutter and a litte confused by the async-await flutter exception handling in this case.

So basically i have this function that loads a .json settings file from the flutter data folder. Its supposed to load the settings and throw a SettingsLoadingException in the case it's unable to find the file, so the calling function knows when to create a new one.

This mechanism works, but two things are confusing me in this case. First of all it's still printing an uncaught FileSystemException to the console even though the print "No settings file!" shows it got caught. Secondly "No settings file" and the error are printed twice - so is it catching two errors?

Future<Settings> loadSettings() async {
  try {
    String fileName = SettingsService.settingsFileName;
    File file = File("${await _localPath}/${dbFolderName}/${fileName}");

    String fileContent = await file.readAsString();
    Map<String, dynamic> settingJsonMap = jsonDecode(fileContent);
    Settings settings = Settings.fromJson(settingJsonMap);

    return settings;
  } catch (e) {
    print("No settings file!");
    throw SettingsLoadingException("Unable to load settings");
  }
}

I/flutter (10533): No settings file!
I/flutter (10533): No settings file!
E/flutter (10533): \[ERROR:flutter/runtime/dart_vm_initializer.cc(41)\] Unhandled Exception: FileSystemException: Cannot open file, path = '/data/user/0/com.yapps.smartdart/app_flutter/db/settings.json' (OS Error: No such file or directory, errno = 2)
E/flutter (10533): #0      \_File.open.\<anonymous closure\> (dart:io/file_impl.dart:356:9)
E/flutter (10533): \<asynchronous suspension\>
E/flutter (10533):
E/flutter (10533): \[ERROR:flutter/runtime/dart_vm_initializer.cc(41)\] Unhandled Exception: FileSystemException: Cannot open file, path = '/data/user/0/com.yapps.smartdart/app_flutter/db/settings.json' (OS Error: No such file or directory, errno = 2)
E/flutter (10533): #0      \_File.open.\<anonymous closure\> (dart:io/file_impl.dart:356:9)
E/flutter (10533): \<asynchronous suspension\>
E/flutter (10533):
E/SurfaceSyncer(10533): Failed to find sync for id=0
W/Parcel  (10533): Expecting binder but got null!

I already tried using the .then and .catchError API which didn't work and led me to a totally different error.

CodePudding user response:

The first thing you're confused about, FileSystemException is and error on the native side of the plugin you're using. So don't worry about that. the error is just getting caught on the plugin side and so does the error message that is being printed.

And The second thing which is messages getting printed twice should not have anything to do with the FileSystemException. My guess is you're calling the method twice. If so, you can confirm this by running this code in debug mode and using break points

  • Related