2021-06-18 12:41:57 +00:00
|
|
|
/*
|
|
|
|
* Copyright (c) 2021 Proton Technologies AG
|
|
|
|
* This file is part of Proton Technologies AG and ProtonCore.
|
|
|
|
*
|
|
|
|
* ProtonCore is free software: you can redistribute it and/or modify
|
|
|
|
* it under the terms of the GNU General Public License as published by
|
|
|
|
* the Free Software Foundation, either version 3 of the License, or
|
|
|
|
* (at your option) any later version.
|
|
|
|
*
|
|
|
|
* ProtonCore is distributed in the hope that it will be useful,
|
|
|
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
* GNU General Public License for more details.
|
|
|
|
*
|
|
|
|
* You should have received a copy of the GNU General Public License
|
|
|
|
* along with ProtonCore. If not, see <https://www.gnu.org/licenses/>.
|
|
|
|
*/
|
|
|
|
|
2021-08-12 16:55:52 +00:00
|
|
|
package me.proton.core.network.data.interceptor
|
2021-06-18 12:41:57 +00:00
|
|
|
|
2021-08-12 16:55:52 +00:00
|
|
|
import me.proton.core.network.data.ProtonErrorException
|
|
|
|
import me.proton.core.network.data.protonApi.ProtonErrorData
|
2021-11-22 10:10:22 +00:00
|
|
|
import me.proton.core.network.domain.exception.ApiConnectionException
|
2021-08-12 16:55:52 +00:00
|
|
|
import me.proton.core.util.kotlin.deserializeOrNull
|
2021-06-18 12:41:57 +00:00
|
|
|
import okhttp3.Interceptor
|
|
|
|
import okhttp3.Response
|
2021-11-22 14:08:54 +00:00
|
|
|
import java.io.IOException
|
2021-06-18 12:41:57 +00:00
|
|
|
|
2021-08-12 16:55:52 +00:00
|
|
|
class ServerErrorInterceptor : Interceptor {
|
2021-06-18 12:41:57 +00:00
|
|
|
|
|
|
|
override fun intercept(chain: Interceptor.Chain): Response {
|
|
|
|
val request = chain.request()
|
2021-11-22 14:08:54 +00:00
|
|
|
val response = try {
|
|
|
|
chain.proceed(request)
|
|
|
|
} catch (e: IOException) {
|
|
|
|
// every IO exception is possible potential blocking of the API
|
2021-11-17 13:20:10 +00:00
|
|
|
with(request.url) {
|
2021-11-22 10:10:22 +00:00
|
|
|
throw ApiConnectionException(encodedPath, query, e)
|
2021-11-22 14:08:54 +00:00
|
|
|
}
|
|
|
|
}
|
2021-08-12 16:55:52 +00:00
|
|
|
if (!response.isSuccessful) {
|
|
|
|
val errorBody = response.peekBody(MAX_ERROR_BYTES).string()
|
|
|
|
val protonError = errorBody.deserializeOrNull(ProtonErrorData.serializer())?.apiResultData
|
|
|
|
if (protonError != null) {
|
|
|
|
throw ProtonErrorException(response, protonError)
|
|
|
|
}
|
|
|
|
}
|
2021-06-18 12:41:57 +00:00
|
|
|
return response
|
|
|
|
}
|
2021-08-12 16:55:52 +00:00
|
|
|
|
|
|
|
companion object {
|
|
|
|
private const val MAX_ERROR_BYTES = 1_000_000L
|
|
|
|
}
|
2021-06-18 12:41:57 +00:00
|
|
|
}
|