android - Retrofit and Response<Void> - Stack Overflow

admin2025-04-17  2

I use retrofit for this request. You can see that the method returns a Response object, which is required to get some information about the progress of the request.

@POST("/test")
    suspend fun sendTest(@Body model: TestModel): Response<Void>

I encountered a surprise in that specifying such a return leads to the fact that in the case of a backend response with the code != 200, the catch branches do not work. In general, it is clear why this is so - telling the retrofit that I want to get a Response from it, it removes responsibility for throwing exceptions. Question: maybe there is some annotation that will indicate that the retrofit should throw an exception with a Response.

I use retrofit for this request. You can see that the method returns a Response object, which is required to get some information about the progress of the request.

@POST("/test")
    suspend fun sendTest(@Body model: TestModel): Response<Void>

I encountered a surprise in that specifying such a return leads to the fact that in the case of a backend response with the code != 200, the catch branches do not work. In general, it is clear why this is so - telling the retrofit that I want to get a Response from it, it removes responsibility for throwing exceptions. Question: maybe there is some annotation that will indicate that the retrofit should throw an exception with a Response.

Share Improve this question edited Jan 31 at 23:53 user1854307 asked Jan 31 at 22:30 user1854307user1854307 6304 gold badges10 silver badges27 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

You should try to catch more exceptions

suspend fun callSendTest(model: TestModel) {
try {
    val response = sendTest(model)
    if (response.isSuccessful) {
    } else {
        println("HTTP Error: ${response.code()}")
    }
} catch (e: IOException) {
    e.printStackTrace()
} catch (e: HttpException) {
    e.printStackTrace()
} catch (e: Exception) {
    e.printStackTrace()
}
}
转载请注明原文地址:http://anycun.com/QandA/1744844472a88411.html