Skip to content

Commit

Permalink
Helper function for fetching errors of specific type (#543)
Browse files Browse the repository at this point in the history
  • Loading branch information
Guldem authored Jan 2, 2024
1 parent 8938d98 commit 4ba5a83
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 0 deletions.
9 changes: 9 additions & 0 deletions chopper/lib/src/response.dart
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,15 @@ base class Response<BodyType> with EquatableMixin {
String get bodyString =>
base is http.Response ? (base as http.Response).body : '';

/// Check if the response is an error and if the error is of type [ErrorType] and casts the error to [ErrorType]. Otherwise it returns null.
ErrorType? errorWhereType<ErrorType>() {
if (error != null && error is ErrorType) {
return error as ErrorType;
} else {
return null;
}
}

@override
List<Object?> get props => [
base,
Expand Down
49 changes: 49 additions & 0 deletions chopper/test/base_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import 'package:http/testing.dart';
import 'package:test/test.dart';
import 'package:transparent_image/transparent_image.dart';

import 'fixtures/error_fixtures.dart';
import 'fixtures/example_enum.dart';
import 'test_service.dart';
import 'test_service_base_url.dart';
Expand Down Expand Up @@ -1649,4 +1650,52 @@ void main() {

httpClient.close();
});

group('Response error casting test', () {
test('Response is succesfull, [returns null]', () {
final base = http.Response('Foobar', 200);

final response = Response(base, 'Foobar');

final result = response.errorWhereType<FooErrorType>();

expect(result, isNull);
});

test('Response is unsuccessful and has no error object, [returns null]',
() {
final base = http.Response('Foobar', 400);

final response = Response(base, '');

final result = response.errorWhereType<FooErrorType>();

expect(result, isNull);
});

test(
'Response is unsuccessful and has error object of different type, [returns null]',
() {
final base = http.Response('Foobar', 400);

final response = Response(base, '', error: 'Foobar');

final result = response.errorWhereType<FooErrorType>();

expect(result, isNull);
});

test(
'Response is unsuccessful and has error object of specified type, [returns error as ErrorType]',
() {
final base = http.Response('Foobar', 400);

final response = Response(base, 'Foobar', error: FooErrorType());

final result = response.errorWhereType<FooErrorType>();

expect(result, isNotNull);
expect(result, isA<FooErrorType>());
});
});
}
3 changes: 3 additions & 0 deletions chopper/test/fixtures/error_fixtures.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
class FooErrorType {
const FooErrorType();
}

0 comments on commit 4ba5a83

Please sign in to comment.