Skip to content

feat: ignoring addError in reported stacktrace #3585

Description

@orestesgaolin

Description

When reading through the stack trace reported when calling addError(Exception('Hello there')); the first frame is always BlocBase.addError. This is because addError() implementation passes StackTrace.current if no stack trace is provided:

  void addError(Object error, [StackTrace? stackTrace]) {
    onError(error, stackTrace ?? StackTrace.current);
  }

Here's a sample report from Crashlytics:

CleanShot 2022-10-21 at 09 32 38@2x

Desired Solution

The BlocBase.addError should be omitted in the stack trace passed to onError if no stack trace is passed to addError.

The solution I used in my BlocObserver is to create new Trace (using stack_trace package) and skip frames related to BlocBase.addError:

  @override
  void onError(BlocBase<dynamic> bloc, Object error, StackTrace stackTrace) {
    var trace = Trace.from(stackTrace);
    // addError obscures the crashlytics reports
    if (trace.frames.isNotEmpty &&
        trace.frames.first.member == 'BlocBase.addError') { // I only care if this is the first frame, otherwise let's not modify the frames
      trace = trace.skipFrames((f) => f.member == 'BlocBase.addError');
    }
    if (kDebugMode) {
      ///
    } else {
      FirebaseCrashlytics.instance.recordError(error, trace);
    }
    super.onError(bloc, error, trace);
  }

//...

extension on Trace {
  Trace skipFrames(bool Function(Frame f) predicate) {
    final newFrames = frames.where((element) => !predicate(element));

    return Trace(newFrames, original: original.toString());
  }
}

Alternatives Considered

  • Omitting the stack trace manually in my BlocObserver
  • Always passing StackTrace.current to addError

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement candidateCandidate for enhancement but additional research is neededpkg:blocThis issue is related to the bloc package

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions