-
Notifications
You must be signed in to change notification settings - Fork 60
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How to handle responses with 200 **AND** 204 (No Content) #44
Comments
I think it will return a when (result) {
is NetworkResponse.Success -> {
// Handle successful response (204)
}
is NetworkResponse.ServerError -> {
if(result.code == 200){
// handle special case
}
// Handle normal server error
}
is NetworkResponse.NetworkError -> {
// Handle network error
}
is NetworkResponse.UnknownError -> {
// Handle other errors
}
} |
@Sharkaboi Yes this works. But I was asking if this would be a good feature to have. Maybe raise a PR. But got engaged with other stuff. |
Consider this example: interface PostsService {
@GET("/")
suspend fun getPost(): NetworkResponse<Post, ErrorResponse>
} When the server responds with a 2xx status code and a In this scenario we have to decide whether you expected a null body or not.
Things get more complicated if the server can respond with both types of bodies in the same API call. For this scenario:
So the real problem here is that you lose access to the response content for // The new Success class
data class Success<S, E>(val body: S, val response: Response<*>): NetworkResponse<S, E>
interface PostsService {
@GET("/")
suspend fun getPost(): NetworkResponse<Unit, ErrorResponse>
}
when (val postResponse = service.getPost()) {
is NetworkResponse.Success -> {
if (postResponse.code != 204) {
val rawBody = postResponse.response.rawBody()
// Manually parse the raw body to access the response
}
}
is NetworkResponse.Error -> { ... }
} You can then always specify the return type as Here's an example of how to deserialize the raw body using the @Serializable
data class Post(...)
val rawBody = postResponse.response.raw().body
val decoded = Json.decodeFromString(Post.serializer(), rawBody.string()) |
We can handle a 204 with
But here the response can only be
Unit
. But what if I can have a 200 responses when there is new content and 204 when there is no new content?The text was updated successfully, but these errors were encountered: