改造 Try&Catch 未按预期工作

Retrofit Try&Catch is not working as I expected

我可以使用 try&catch 捕获 IOException,但无法使用 try&catch 捕获 HttpException。我尝试使用 if else 条件捕获错误代码 401,它正在运行。

问题是在这种情况下,为什么 try&catch 方法无法捕获错误代码 401?我该怎么办?

override suspend fun wallpaperByTagRepo(tag: String,page: Int): Flow<Resource<List<WallPaper>>> = flow {

       emit(Resource.Loading())

        try {
            val response = remoteDataSource.wallpaperByTagDS(tag, page)
            if (response.isSuccessful){

                val body = response.body()
                body?.let { dto ->
                    val data = dto.toWallPaper()
                    emit(Resource.Success(data = data))
                }
            }
            else{
                when(response.code()){
                    401 -> {
                        Log.w(TAG,"401 Unauthorized")
                    }
                }
            }
        }

        catch (e: IOException){
            emit(Resource.Error("Please check your connection..."))

        }
        catch (e:HttpException){
            emit(Resource.Error("Unexpected error, please try later..."))
            Log.w(TAG,"${e.code()}")

        }

    }

}

在非 2xx HTTP 响应的情况下,Retrofit 不会抛出 retrofit2.HttpException。在这种情况下,您可以从意外响应中手动构造一个 retrofit2.HttpException 对象,例如:

try {
    //
    if (response.isSuccessful) {
        //
    } else {
        throw HttpException(response)
    }
} catch (e: IOException) {
    //
} catch (e: HttpException) {
    //
}