felangel / felangel/bloc

feat: ignoring addError in reported stacktrace

Open
#3,585 2 comments 0 reactions 0 assignees View on GitHub
enhancement candidate pkg:bloc
Dominant language
Dart
Stars
12.5k
Forks
3.4k
PR merge metrics
No merged PRs in 30d

Description

**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:

```dart
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](https://user-images.githubusercontent.com/16854239/197139256-894d34bd-24db-4601-a996-520c61e91550.png)

**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`:

```dart
@override
void onError(BlocBase 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`

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.