Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve HTTP error messages #19

Merged
merged 2 commits into from
Nov 17, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 28 additions & 3 deletions lib/src/streaming_sync.dart
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ class StreamingSyncImplementation {
}
}
if (response.statusCode != 200) {
throw HttpException(response.reasonPhrase ?? "Request failed", uri: uri);
throw getError(response);
}

final body = convert.jsonDecode(response.body);
Expand Down Expand Up @@ -294,8 +294,7 @@ class StreamingSyncImplementation {
}
}
if (res.statusCode != 200) {
throw HttpException(res.reasonPhrase ?? 'Invalid http response',
uri: uri);
throw await getStreamedError(res);
}

// Note: The response stream is automatically closed when this loop errors
Expand All @@ -304,3 +303,29 @@ class StreamingSyncImplementation {
}
}
}

HttpException getError(http.Response response) {
try {
final body = response.body;
final decoded = convert.jsonDecode(body);
final details = decoded['error']?['details']?[0] ?? body;
final message = '${response.reasonPhrase ?? "Request failed"}: $details';
return HttpException(message, uri: response.request?.url);
} on Error catch (_) {
return HttpException(response.reasonPhrase ?? "Request failed",
uri: response.request?.url);
}
}

Future<HttpException> getStreamedError(http.StreamedResponse response) async {
try {
final body = await response.stream.bytesToString();
final decoded = convert.jsonDecode(body);
final details = decoded['error']?['details']?[0] ?? body;
final message = '${response.reasonPhrase ?? "Request failed"}: $details';
return HttpException(message, uri: response.request?.url);
} on Error catch (_) {
return HttpException(response.reasonPhrase ?? "Request failed",
uri: response.request?.url);
}
}