Bloc: Top Level Error Handling

Created on 7 Jun 2019  路  5Comments  路  Source: felangel/bloc

I love using this package and I was wondering what the right way of hanling Top level errors for my mapEventToState callback would be. The following snippet although doesn't work tries to explain what I want to do

`

@override
  Stream<ProductState> mapEventToState(
    ProductEvent event,
  ) async* {
  try{
      if(event is AddProductToWishList)
        yield* _addProductToWishListMTS();
      else if(event is AddProductToCart)
        yield* _addProductToCartMTS(event.cartItem);
      else if(event is ChangeProductState)
        yield* _changeProductStateMTS();
 }catch(e){
     yield ErrorState():
} }
Stream _addProductToWishListMTS()async*{
    //does something that may throw an error
}

`

question

Most helpful comment

Thank u so much for your fast reply.I dispatched a new event inside the onError which will be mapped to an ErrorState. Keep going with this very predictable and awesome library!!

All 5 comments

Hi @iBrave-dev 馃憢
Thanks so much for the positive feedback and for opening an issue!

Regarding your question, you can handle errors at the bloc level by overriding onError like:

@override
void onError(Object error, StackTrace stacktrace) {    
  super.onError(error, stacktrace);
  // handle bloc-specific errors here
}

Alternatively, if you want global error handling for all blocs you can override onError in your own BlocDelegate like so:

@override
void onError(Bloc bloc, Object error, StackTrace stacktrace) {
  super.onError(bloc, error, stacktrace);
  // handle global bloc errors here
}

Hope that helps! Let me know if you have any additional questions 馃憤

Thank u so much for your fast reply.I dispatched a new event inside the onError which will be mapped to an ErrorState. Keep going with this very predictable and awesome library!!

No problem! I think I might've misunderstood your question though. You should not need to dispatch another event in onError because you should be able to just yield the error state in your catch block. Can you please provide a link to some sample code which illustrates the problem you were having with your initial approach? Thanks!

Checkout this demo https://github.com/iBrave-dev/demo/blob/f7c7e73a8786807dc85d2cf2791ee66afe26d0d3/demo.dart#L1-L33

All I want to do is handle all error of my map to state functions (async* functions) from one place and yield an errorState to the UI so that it may display an error toast

I think that should work if you change line 20 to

yield await AiRepository().addToWishList(productModel);
Was this page helpful?
0 / 5 - 0 ratings

Related issues

MahdiPishguy picture MahdiPishguy  路  3Comments

RobPFarley picture RobPFarley  路  3Comments

Reidond picture Reidond  路  3Comments

timtraversy picture timtraversy  路  3Comments

1AlexFix1 picture 1AlexFix1  路  3Comments