Skip to content

Commit 5303fc5

Browse files
committed
duplicate response status checks on response exception
Signed-off-by: Adam Ratzman <[email protected]>
1 parent bf7f9ee commit 5303fc5

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

src/commonMain/kotlin/com.adamratzman.spotify/http/HttpConnection.kt

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,29 @@ public class HttpConnection constructor(
144144
} catch (e: ResponseException) {
145145
val errorBody = e.response.readText()
146146
try {
147+
if (e.response.status.value == 429) {
148+
val ratelimit = e.response.headers["Retry-After"]!!.toLong() + 1L
149+
if (api?.spotifyApiOptions?.retryWhenRateLimited == true) {
150+
api.logger.logError(
151+
false,
152+
"The request ($url) was ratelimited for $ratelimit seconds at ${getCurrentTimeMs()}",
153+
null
154+
)
155+
156+
delay(ratelimit * 1000)
157+
return execute(additionalHeaders, retryIfInternalServerError = retryIfInternalServerError)
158+
} else throw SpotifyRatelimitedException(ratelimit)
159+
}
160+
161+
if (e.response.status.value == 401 && errorBody.contains("access token") &&
162+
api != null && api.spotifyApiOptions.automaticRefresh
163+
) {
164+
api.refreshToken()
165+
val newAdditionalHeaders = additionalHeaders?.toMutableList() ?: mutableListOf()
166+
newAdditionalHeaders.add(0, HttpHeader("Authorization", "Bearer ${api.token.accessToken}"))
167+
return execute(newAdditionalHeaders, retryIfInternalServerError)
168+
}
169+
147170
val error = errorBody.toObject(
148171
ErrorResponse.serializer(),
149172
api,

0 commit comments

Comments
 (0)