mobx.dart icon indicating copy to clipboard operation
mobx.dart copied to clipboard

The exception does not work within the reaction

Open kirill09 opened this issue 2 years ago • 2 comments

Hi. Found an interesting bug. If method which processes reaction is not async then exception is not displayed in console and Guarded doesn't work.

reaction((_) => name, validateUsername),
....
// No exception
@action
void validateUsername(String value) {
  print('validateUsername');
  throw Exception('Test exception');
}

// Exception works
@action
Future<void> validateUsernameAsync(String value) async {
  print('validateUsernameAsync');
  throw Exception('Test exception');
}

I did not find any mention of this feature in the documentation. Why does this happen and is this a bug or normal? I think this should be described in the documentation

kirill09 avatar Aug 22 '22 18:08 kirill09

@kirill09 https://mobx.netlify.app/api/context#reactiveconfig

disableErrorBoundaries: When true, MobX will not guard against exceptions thrown during reactions. By default, it is false, which means MobX will catch unhandled exceptions and ensure the consistency of the reactive system.

https://github.com/mobxjs/mobx.dart/blob/cea7013fad1fcdfbb3213045db9be5e3f311f2f3/mobx/lib/src/core/reaction.dart#L172

https://mobx.js.org/configuration.html#disableerrorboundaries-boolean

By default, MobX will catch and re-throw exceptions happening in your code to make sure that a reaction in one exception does not prevent the scheduled execution of other, possibly unrelated, reactions. This means exceptions are not propagated back to the original causing code and therefore you won't be able to catch them using try/catch.

By disabling error boundaries, exceptions can escape derivations. This might ease debugging, but might leave MobX and by extension your application in an unrecoverable broken state. Default: false.

https://github.com/mobxjs/mobx.dart/blob/cea7013fad1fcdfbb3213045db9be5e3f311f2f3/mobx/test/reaction_test.dart#L222

I think mobx should not throw exception in reaction. Even if it is an async action, mobx should not throw an exception. And if you need error handling, you can use onError .

reaction((_) => name, validateUsername, onError: (e, r) {
      error = e;
      print('error');
    }),

amondnet avatar Oct 03 '22 09:10 amondnet

https://mobx.js.org/api.html#onreactionerror

amondnet avatar Dec 27 '23 07:12 amondnet