Skip to content

Commit

Permalink
chore: Deserialize errors in HTTP client (#140)
Browse files Browse the repository at this point in the history
  • Loading branch information
dnys1 authored May 29, 2024
1 parent 02bf538 commit 9701b82
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 9 deletions.
4 changes: 4 additions & 0 deletions packages/celest_core/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
## 0.4.1

- chore(core): Deserialize errors returned from backend

## 0.4.0

This release introduces support for HTTP customization, improved ergonomics, and a preview of running Flutter and UI code in the sky!
Expand Down
36 changes: 27 additions & 9 deletions packages/celest_core/lib/src/base/base_protocol.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import 'dart:convert';
import 'package:celest_core/celest_core.dart';
import 'package:celest_core/src/base/celest_base.dart';
import 'package:http/http.dart' as http;
import 'package:http_parser/http_parser.dart';

mixin BaseProtocol {
CelestBase get celest;
Expand Down Expand Up @@ -40,15 +41,32 @@ mixin BaseProtocol {
'content-type': 'application/json',
},
);
if (resp.statusCode == 401) {
throw UnauthorizedException();
}
if (resp.statusCode != 200) {
throw http.ClientException(
'${resp.statusCode}: ${resp.body}',
uri,
);
return switch (resp.statusCode) {
200 => jsonDecode(resp.body) as Map<String, Object?>,
400 => _error(resp, BadRequestException.new),
401 => _error(resp, UnauthorizedException.new),
500 => _error(resp, InternalServerError.new),
_ => throw http.ClientException(
'${resp.statusCode}: ${resp.body}',
uri,
),
};
}

Never _error<T extends Object>(
http.Response response,
T Function(String message) createError,
) {
final mediaType = switch (response.headers['content-type']) {
final contentType? => MediaType.parse(contentType),
_ => throw createError(response.body),
};
if (mediaType.mimeType != 'application/json') {
throw createError(response.body);
}
return jsonDecode(resp.body) as Map<String, Object?>;
final json = jsonDecode(response.body) as Map<String, Object?>;
final error = json['error'] as Map<String, Object?>?;
final message = error?['message'] as String?;
throw createError(message ?? response.body);
}
}
1 change: 1 addition & 0 deletions packages/celest_core/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ dependencies:
os_detect: ^2.0.1
path: ^1.9.0
native_storage: ^0.1.0
http_parser: ^4.0.2

dev_dependencies:
lints: ^4.0.0
Expand Down

0 comments on commit 9701b82

Please sign in to comment.