Created
April 7, 2024 13:04
-
-
Save KovshefulCoder/e546ed1f0979af56ac51e8a02eafc5f2 to your computer and use it in GitHub Desktop.
Safe deserializeErrorBody for skydoves/sandwich library
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package ru.kovsharev.porykam.core.utils | |
import com.skydoves.sandwich.ApiResponse | |
import com.skydoves.sandwich.retrofit.serialization.deserializeErrorBody | |
import kotlinx.serialization.SerializationException | |
import kotlinx.serialization.json.Json | |
/** | |
* Deserializes the Json string from error body of the [ApiResponse.Failure.Error] to the [E] custom type. | |
* It returns `null` if the error body is empty or catched exception. | |
* | |
* @param json [Json] instance that could be configured as needed. | |
* | |
* @throws SerializationException in case of any decoding-specific error | |
* @throws IllegalArgumentException if the decoded input is not a valid instance of [E] | |
* | |
* @author KovshefulCoder | |
*/ | |
inline fun <T, reified E> ApiResponse<T>.safeDeserializeErrorBody( | |
json: Json = Json, | |
onSerializationException: (SerializationException) -> Unit = {}, | |
onIllegalArgumentException: (IllegalArgumentException) -> Unit = {} | |
): E? { | |
return try { | |
this.deserializeErrorBody(json = json) | |
} catch (e: SerializationException) { | |
onSerializationException(e) | |
null | |
} catch (e: IllegalArgumentException) { | |
onIllegalArgumentException(e) | |
null | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment