Skip to content

catchError and onError do not catch error with function without "async" keyword #50361

@kaboc

Description

@kaboc
Future<void> main() async {
  final result = await calcOrThrow(-10).onError((e, s) => 0);
  print(result);
}

Future<int> calcOrThrow(int value) { // No "async" keyword here
  if (value < 0) {
    throw Exception('ERROR');
  }
  return calc(value);
}

Future<int> calc(int value) async {
  return value * 2;
}

Unhandled exception:
Exception: ERROR

It occurred only with some functions, so I compared with other functions and found that it depended on whether a function had the "async" keyword. If I add async to calcOrThrow() above, onError() can catch the exception thrown there.

Future<int> calcOrThrow(int value) async {

However, it is possible to omit async because calcOrThrow() directly returns the future returned from calc(). The analyzer warns nothing about it, so I think this misuse (or a bug?) can easily happen.

It is also confusing that try-catch worked fine regardless of async.

Future<void> main() async {
  try {
    final result = await calcOrThrow(-10);
    print(result);
  } on Exception {
    print(0);
  }
}

Future<int> calcOrThrow(int value) { // No "async" keyword here
  ...
}

It seems this issue exists in whenComplete() and the onError argument of then() too.

Metadata

Metadata

Assignees

No one assigned

    Labels

    closed-as-intendedClosed as the reported issue is expected behavior

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions