|
| 1 | +/* |
| 2 | + * Copyright (c) 2014-2025 Stream.io Inc. All rights reserved. |
| 3 | + * |
| 4 | + * Licensed under the Stream License; |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * https://github.com/GetStream/stream-core-android/blob/main/LICENSE |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package io.getstream.android.core.internal.http.interceptor |
| 17 | + |
| 18 | +import io.getstream.android.core.api.model.exceptions.StreamEndpointErrorData |
| 19 | +import io.getstream.android.core.api.model.exceptions.StreamEndpointException |
| 20 | +import io.getstream.android.core.api.serialization.StreamJsonSerialization |
| 21 | +import kotlin.fold |
| 22 | +import kotlin.jvm.java |
| 23 | +import okhttp3.Interceptor |
| 24 | +import okhttp3.Response |
| 25 | + |
| 26 | +/** |
| 27 | + * Interceptor that handles API errors by parsing the response body and throwing a |
| 28 | + * [StreamEndpointException]. |
| 29 | + * |
| 30 | + * @param jsonParser The JSON parser to parse the error response. |
| 31 | + */ |
| 32 | +internal class StreamEndpointErrorInterceptor(private val jsonParser: StreamJsonSerialization) : |
| 33 | + Interceptor { |
| 34 | + |
| 35 | + override fun intercept(chain: Interceptor.Chain): Response { |
| 36 | + val response = chain.proceed(chain.request()) |
| 37 | + |
| 38 | + if (!response.isSuccessful) { |
| 39 | + // Try to parse a Stream API error from the response body |
| 40 | + val errorBody = response.peekBody(Long.MAX_VALUE).string() |
| 41 | + jsonParser |
| 42 | + .fromJson(errorBody, StreamEndpointErrorData::class.java) |
| 43 | + .fold( |
| 44 | + onSuccess = { apiError -> |
| 45 | + throw StreamEndpointException( |
| 46 | + "Failed request: ${chain.request().url}", |
| 47 | + apiError, |
| 48 | + ) |
| 49 | + }, |
| 50 | + onFailure = { error -> |
| 51 | + throw StreamEndpointException( |
| 52 | + message = "Failed request: ${chain.request().url}", |
| 53 | + cause = error, |
| 54 | + ) |
| 55 | + }, |
| 56 | + ) |
| 57 | + } |
| 58 | + return response |
| 59 | + } |
| 60 | +} |
0 commit comments