I see people use onError
just for debugging. I thought I could use it to emit new states like emit(ErrorState(message: "An error"))
. But with the new versions of the bloc package, we should use emitters provided to the handlers and shouldn't use the dedicated function emit
directly.
Currently I have try/catch blocks in all of my event handlers. If any error occurs, I emit the ErrorState
with a message and show it in the UI with a widget. Is this how should I handle errors? This makes event handler functions to look awful with these try/catchs. I wonder if I'm doing it correct and want to know how should it be done actually?
void _startExercise(ExerciseStarted event, Emitter<ExerciseState> emit) async {
emit(ExerciseLoadingState());
try {
final something = await _repository.doSomething();
emit(ExerciseLoadedState(something: something));
} catch (e) {
log(e.toString());
emit(const ExerciseErrorState());
}
}
Well, let's separate this problem into two parts:
In this case, your provided code example is doing it properly - you have to use try/catch and emit an error state in case of an Error/Exception. The only thing I would adjust there is to change catch (e) {...}
to on Exception catch (e) {...}
since Dart errors must be handled in your code and you could simply miss them in case you catch everything there.
In this case, you can handle errors inside the repository. E.g. use the try/catch block inside the repository and log the error. Since you do not need to emit a state change, the error will be handled and also your event handler won't be cluttered with this extra try/catch logic.
Anyway, whichever way you choose, just be consistent and you should be good to go.