Skip to content

Commit

Permalink
Improve rate limit handling (Closes #37)
Browse files Browse the repository at this point in the history
  • Loading branch information
BjoernPetersen committed Mar 3, 2023
1 parent fba8a43 commit 3a905af
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 4 deletions.
6 changes: 5 additions & 1 deletion CHANGELOG.md
@@ -1,6 +1,10 @@
# Changelog

## [Unreleased]
## [Unreleased] 0.4.0-alpha

- Improve error handling
- RateLimitingException now contains the duration after which a retry should be done
- Not attempt is made to decode rate limiting error responses (they're not JSON)

### Breaking Changes

Expand Down
14 changes: 12 additions & 2 deletions lib/src/api/core.dart
Expand Up @@ -58,15 +58,25 @@ class CoreApi implements SpotifyWebApi {

void checkErrors(Response response) {
if (!response.isSuccessful) {
final body = response.body.decodeJson(ErrorResponse.fromJson);
switch (response.statusCode) {
case 401:
throw AuthenticationException();
case 403:
throw AuthorizationException();
case 429:
throw RateLimitException();
final retryAfterSeconds = response.header('Retry-After');

if (retryAfterSeconds == null) {
throw RateLimitException(null);
}

throw RateLimitException(
DateTime.now()
.toUtc()
.add(Duration(seconds: int.parse(retryAfterSeconds))),
);
default:
final body = response.body.decodeJson(ErrorResponse.fromJson);
throw SpotifyApiException(body.error.message);
}
}
Expand Down
6 changes: 5 additions & 1 deletion lib/src/exceptions.dart
Expand Up @@ -18,4 +18,8 @@ class AuthenticationException extends SpotifyApiException {}

class AuthorizationException extends SpotifyApiException {}

class RateLimitException extends SpotifyApiException {}
class RateLimitException extends SpotifyApiException {
final DateTime? retryAfter;

RateLimitException(this.retryAfter);
}
2 changes: 2 additions & 0 deletions lib/src/requests.dart
Expand Up @@ -61,6 +61,8 @@ class Response {

bool get isSuccessful => statusCode >= 200 && statusCode < 300;

String? header(String headerName) => _response.headers[headerName];

ResponseBody get body => ResponseBody(_response.bodyBytes);
}

Expand Down

0 comments on commit 3a905af

Please sign in to comment.