Using Retrofit with Kotlin Coroutines and Handling 401 Unauthorized Responses in Android 14
I'm building a feature where I'm upgrading from an older version and I've encountered a strange issue with I've been struggling with this for a few days now and could really use some help. After trying multiple solutions online, I still can't figure this out. I'm currently working on an Android app using Retrofit for network calls and Kotlin Coroutines for asynchronous programming. I've set up my Retrofit instance and everything seems to work fine until I encounter a 401 Unauthorized response from my API. Instead of handling this gracefully, I get an unhandled exception that crashes my app. I'm using Retrofit 2.9.0 and Kotlin 1.6. I want to catch this error and redirect the user to the login activity without crashing the app. Here's a simplified version of my Retrofit setup: ```kotlin val retrofit = Retrofit.Builder() .baseUrl("https://api.example.com/") .addConverterFactory(GsonConverterFactory.create()) .build() ``` And here's my API service: ```kotlin interface ApiService { @GET("/user/profile") suspend fun getUserProfile(): Response<UserProfile> } ``` In my repository class, I'm making the network call like this: ```kotlin class UserRepository(private val apiService: ApiService) { suspend fun fetchUserProfile() { val response = apiService.getUserProfile() if (response.isSuccessful) { return response.body() } else { // Handle error } } } ``` In the error handling part, I want to check if the response code is 401. But currently, I'm getting a `kotlinx.coroutines.CancellationException` when the token is invalid. I've tried wrapping the network call in a try-catch block, but it doesn't seem to catch the exception. Any suggestions on how to properly handle 401 errors using Retrofit with coroutines? Should I look into a different approach for error handling or is there a specific way to manage this scenario? I'm working on a API that needs to handle this. This is part of a larger CLI tool I'm building. Thanks in advance! This is happening in both development and production on Ubuntu 22.04. What am I doing wrong? I'm working in a Windows 11 environment. I'd be grateful for any help.