Skip to content

Instantly share code, notes, and snippets.

@jetaggart
Last active February 22, 2019 14:35
Show Gist options
  • Save jetaggart/abf65c6155c8afecf0dd24dead431185 to your computer and use it in GitHub Desktop.
Save jetaggart/abf65c6155c8afecf0dd24dead431185 to your computer and use it in GitHub Desktop.
// BLOC
class ErrorBloc extends Bloc<ErrorBlocEvent, ErrorBlocState> {
@override
Stream<ClaimState> mapEventToState(ErrorBlocState currentState, ErrorBlocEvent event) async* {
if (event is SomeEvent) {
yield Processing();
final result = await _doSomething();
if(result.success) {
yield Success();
} else {
// yield error state so widget can handle gracefully
yield Failure();
// throw exception so error handling can help in background
throw Exception('something went wrong');
}
} else {
throw InvalidEventException(event);
}
}
// ... rest of implementation
}
class ErrorBlocDelegate implements BlocDelegate {
ErrorBlocDelegate(this.errorReporter);
final ErrorReporter errorReporter;
@override
void onError(Object error, StackTrace stacktrace) {
errorReporter.report(error, stacktrace);
}
@override
void onTransition(Transition transition) {
// ignore
}
}
class ErrorReporter {
ErrorReporter(this.env);
final Environment env;
Future<void> report(Object error, StackTrace stackTrace) async {
if (isInDebugMode) {
print(error);
print(stackTrace);
} else {
final user = await _user();
env.sentry.capture(
event: Event(
exception: error,
stackTrace: stackTrace,
userContext: User(
id: user,
),
),
);
}
}
bool get isInDebugMode {
// Assume we're in production mode
var inDebugMode = false;
// Assert expressions are only evaluated during development. They are ignored
// in production. Therefore, this code will only turn `inDebugMode` to true
// in our development environments!
assert(inDebugMode = true);
return inDebugMode;
}
Future<String> _user() async {
// get user
}
}
// in app.dart or wherever is appropriate
BlocSupervisor().delegate = ErrorBlocDelegate(errorReporter);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment