Bloc: Shed some light on error reporting

Created on 18 Nov 2020  路  3Comments  路  Source: felangel/bloc

I've been using this library for a few days now, and I think it's excellent.

One thing that I'm not getting yet though, is how errors are supposed to be shown to the user.

I saw that there is an addError() method in Blocs but that actually triggers the error to be thrown by the stream. What I'm looking for is a way to report something to the user.

Let's use the form example: how should I transport an error message to the UI if there was a problem submitting the form (for example: invalid data). Should I have a try/catch in the bloc, and then an error property on my State class?

It would be great if there was an example (or if the existing examples would be updated) to contain common error handling too.

question

All 3 comments

Hi @enyo 馃憢
Thanks for opening an issue and for the positive feedback! 馃檹

Regarding your question addError is used to report an internal bloc error and it will trigger onError in both the bloc as well as BlocObserver.

Generally, blocs should catch any exceptions from their dependencies and convert them into a state for the UI to respond to:

@override
Stream<MyState> mapEventToState(MyEvent event) async* {
  try {
    final result = await _myRepository.fetch(...);
    yield MyState.success(...);
  } on Exception catch (error, stackTrace) {
    yield MyState.failure(...);
  }
}

An example of this can be seen in the flutter_weather example.

As far as validation errors, I would highly recommend checking out the flutter_form_validation example.

Hope that helps 馃憤

Thanks! I've looked at the form example and it handles everything but the part where the server could report an error (eg: the user tries to register but the email is already taken).

So am I right to assume that in that case, I should simply add an error message or code to the state that the UI can then display?

Yup, that's correct 馃憤

Was this page helpful?
0 / 5 - 0 ratings

Related issues

shawnchan2014 picture shawnchan2014  路  3Comments

hivesey picture hivesey  路  3Comments

nerder picture nerder  路  3Comments

ricktotec picture ricktotec  路  3Comments

abinvp picture abinvp  路  3Comments