Skip to content

"on Exception" Doesn't Handle TypeError in External Data Validation #60024

@behzodfaiziev

Description

@behzodfaiziev

Dart SDK Version: 3.6.1
Flutter Version: 3.27.3

Problem description:

I am trying to follow the avoid_catches_without_on_clauses linter rule by using on Exception for error handling. However, I’ve encountered an issue where TypeError (a subclass of Error) isn’t caught when processing invalid external data (e.g., API responses). The linter flag for using catch (e) forces me to use on Exception, but this doesn’t catch TypeError, leading to test failures when dealing with invalid data types in API responses.

Expected Behavior:

  • on Exception should catch errors like TypeError, which occur during external data validation.

Actual Behavior:

  • on Exception does not catch TypeError, causing the test to fail when an invalid type is encountered.

Steps to reproduce: First Option

Test Code: Line 152

test('should return null tokens when tokens are not strings', () {  
  final response = Response<dynamic>(  
    requestOptions: RequestOptions(path: '/test'),  
    data: <String, dynamic>{  
      'accessToken': 12345, // int (invalid)  
      'refreshToken': true, // bool (invalid)  
    },  
  );  

  final tokens = netKitManager.extractTokens(response: response);  
  expect(tokens.accessToken, isNull);  
  expect(tokens.refreshToken, isNull);  
});

Implementation Code: Line 29

  AuthTokenModel extractTokens({required Response<dynamic> response}) {
    try {
      if ((response.statusCode ?? 0) >= HttpStatus.internalServerError) {
        return const AuthTokenModel();
      }

      // Ensure response.data is treated as a Map
      final data = response.data as Map<String, dynamic>?;

      if (data == null) {
        return const AuthTokenModel();
      }

      return AuthTokenModel(
        accessToken: data[parameters.accessTokenBodyKey] as String?, // Throws TypeError  
        refreshToken: data[parameters.refreshTokenBodyKey] as String?,
      );
    } on Exception catch (_) {
      return const AuthTokenModel(); // catch should have been executed on errro
    }
  }

Steps to Reproduce: Second option

  1. Clone the repository NetKit
  2. After getting the packages run:
cd packages/net-kit && dart test
  1. see error:
'NetKitManager Extract tokens from body should return null tokens when tokens are not strings'
00:04 +57 -1: Some tests failed.

Behavior

With on Exception:

❌ Test fails (TypeError propagates and isn't caught by on Exception).

With catch (e) (violates the linter rule):

⚠️ Test passes (tokens are null), but the linter warns about using catch (e).

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions