How to get response status in Retrofit (Kotlin)?

2 min read 06-10-2024
How to get response status in Retrofit (Kotlin)?


Understanding Response Status Codes in Retrofit (Kotlin)

Retrofit is a powerful library for making network requests in Android and Kotlin. When you make a request, you receive a response from the server. This response contains valuable information, including the status code.

The Problem: You need to know the status code of your Retrofit response to understand if the request was successful or not, and if not, why it failed.

The Solution: Retrofit provides a straightforward way to access the response status code. This article will guide you through the process.

Setting the Stage

Let's say you're making a request to fetch user data from an API using Retrofit. Here's a simple example:

interface ApiService {
    @GET("users/{id}")
    suspend fun getUser(@Path("id") userId: Int): Response<User>
}

This interface defines a function getUser that takes a user ID as input and returns a Response<User> object.

Accessing the Response Status Code

To retrieve the response status code, you can use the following approach:

// Get the response object
val response: Response<User> = apiService.getUser(userId)

// Check if the request was successful
if (response.isSuccessful) {
    // Access the user data
    val user = response.body()
    // ...
} else {
    // Handle the error based on the status code
    when (response.code()) {
        404 -> {
            // User not found
            // ...
        }
        500 -> {
            // Internal server error
            // ...
        }
        else -> {
            // Handle other errors
            // ...
        }
    }
}

Explanation:

  1. Retrieving the response: We first make the API call using the apiService.getUser function and store the response in a Response<User> object.
  2. Checking for success: We use response.isSuccessful to verify if the request was successful (HTTP status code 200-299).
  3. Accessing data: If successful, we can access the user data using response.body().
  4. Handling errors: If the request fails, we use response.code() to get the specific HTTP status code and provide relevant error handling based on the code.

Understanding HTTP Status Codes

Here are some common HTTP status codes and their meanings:

  • 200 OK: The request was successful.
  • 400 Bad Request: The request was invalid (e.g., missing parameters).
  • 401 Unauthorized: The user is not authorized to access the resource.
  • 403 Forbidden: The user is forbidden from accessing the resource, even if authenticated.
  • 404 Not Found: The requested resource was not found.
  • 500 Internal Server Error: The server encountered an error.
  • 503 Service Unavailable: The server is temporarily unavailable.

Going Deeper: Custom Error Handling

For more complex scenarios, you can create custom error handling strategies. For example, you can define a custom ApiException class to encapsulate error details and handle different error types with specific logic:

class ApiException(val code: Int, val message: String?) : Exception(message)

You can then modify your code to throw an ApiException based on the response code:

if (response.isSuccessful) {
    // ...
} else {
    // Handle errors
    throw ApiException(response.code(), response.message())
}

This allows you to handle different errors consistently and provides more control over error management.

Conclusion

Understanding how to retrieve response status codes in Retrofit is essential for building robust and reliable applications. By utilizing the response.isSuccessful and response.code() methods, you can handle successful requests and provide appropriate error handling for failed requests, enhancing the user experience of your application.