Skip to content

Commit f36a41a

Browse files
committed
Extract common logic.
1 parent eb8396e commit f36a41a

File tree

1 file changed

+23
-16
lines changed

1 file changed

+23
-16
lines changed

packages/powersync_core/lib/src/exceptions.dart

Lines changed: 23 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -38,34 +38,41 @@ class SyncResponseException implements Exception {
3838
http.StreamedResponse response) async {
3939
try {
4040
final body = await response.stream.bytesToString();
41-
final decoded = convert.jsonDecode(body);
42-
final details = _stringOrFirst(decoded['error']?['details']) ?? body;
43-
final message = '${response.reasonPhrase ?? "Request failed"}: $details';
44-
return SyncResponseException(response.statusCode, message);
41+
return _fromResponseBody(response, body);
4542
} on Exception catch (_) {
46-
return SyncResponseException(
47-
response.statusCode,
48-
response.reasonPhrase ?? "Request failed",
49-
);
43+
// Could be FormatException, stream issues, or possibly other exceptions.
44+
// Fallback to just using the response header.
45+
return _fromResponseHeader(response);
5046
}
5147
}
5248

5349
/// Parse an error response from the PowerSync service
5450
static SyncResponseException fromResponse(http.Response response) {
5551
try {
5652
final body = response.body;
57-
final decoded = convert.jsonDecode(body);
58-
final details = _stringOrFirst(decoded['error']?['details']) ?? body;
59-
final message = '${response.reasonPhrase ?? "Request failed"}: $details';
60-
return SyncResponseException(response.statusCode, message);
53+
return _fromResponseBody(response, body);
6154
} on Exception catch (_) {
62-
return SyncResponseException(
63-
response.statusCode,
64-
response.reasonPhrase ?? "Request failed",
65-
);
55+
// Could be FormatException, or possibly other exceptions.
56+
// Fallback to just using the response header.
57+
return _fromResponseHeader(response);
6658
}
6759
}
6860

61+
static SyncResponseException _fromResponseBody(
62+
http.BaseResponse response, String body) {
63+
final decoded = convert.jsonDecode(body);
64+
final details = _stringOrFirst(decoded['error']?['details']) ?? body;
65+
final message = '${response.reasonPhrase ?? "Request failed"}: $details';
66+
return SyncResponseException(response.statusCode, message);
67+
}
68+
69+
static SyncResponseException _fromResponseHeader(http.BaseResponse response) {
70+
return SyncResponseException(
71+
response.statusCode,
72+
response.reasonPhrase ?? "Request failed",
73+
);
74+
}
75+
6976
int statusCode;
7077
String description;
7178

0 commit comments

Comments
 (0)