How to handle errors with BLoC?
Asked Answered
L

1

6

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());
    }
  }

Lois answered 5/6, 2022 at 6:11 Comment(1)
It is a common practice to do this. Not sure how handler emitters can handle all edge cases.Redstart
H
4

Well, let's separate this problem into two parts:

  1. You get an error and you want to emit/change the state.

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.

  1. You get an error and just want to handle it.

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.

Homespun answered 8/9, 2022 at 10:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.