Home > other >  Flutter: keep Stacktrace of an error with try catch
Flutter: keep Stacktrace of an error with try catch

Time:09-03

myCrashingFunc() {
  var a = [];
  print(a[0]);
}

try {
  myCrashingFunc()
} catch (e) {
  print(StackTrace.current.toString());
}

Actually, when I debug, I let everything crash so my StackTrace get me to the crashing line.

When I send my app in prod, I use try catch so new errors have default behavior handle.

Problem: with try catch, my Stacktrace stop in the catch, I would like to see the StackTrace give me insigh of the try. (ex: here my StackTrace will only go to the line print(StackTrace.current.toString());

Question: How can I get StackTrace of the function in the try. (ex: hre I would like to see my StackTrace go to line print(a[0]);)

CodePudding user response:

You can access the stacktrace if you pass it as the second argument to catch as follows:

   myCrashingFunc() {
      var a = [];
      print(a[0]);
    }
    
    try {
      myCrashingFunc()
    } on Exception catch (e, s) {
      print(s);
    }
  • Related