简略的问题:
我想从okhttp3.Response中读取自定义错误,就像从retrofit2.Response!中读取一样
的详细问题:
在okhttp3身份验证器上,我希望读取响应自定义错误,以检查我的401是否与令牌过期有关,然后尝试继续使用身份验证方法并使用新令牌创建新请求。后端gimme这样的自定义错误,我可以读取它的枚举类型(作为代码),然后决定下一步要做什么。
{
"timestamp": "2020-11-24T16:55:03.365+09:00",
"status": 401,
"code": "UNAUTHENTICATED_USER",
"message": "The user is not authenticated",
"path": "/members"
}因此,主要的问题是我无法从okhttp3.Response!读取自定义错误消息。虽然我可以在retrofit2.Response中这样做:
@Keep
data class CustomError(
val timestamp: String?,
val status: Int,
val code: ErrorCodes,
val message: String?,
val path: String?
)
fun generateCustomError(response : Response<Any>):CustomError {
return try {
val gson = Gson()
val myError: CustomError = gson.fromJson(
response.errorBody()?.charStream(),
CustomError::class.java
)
myError
}catch (e: Exception){
CustomError(null,response.code(),ErrorCodes.UNKNOWN,response.message(),null)
}
}但似乎okhttp3.Response没有任何errorBody。那么我如何生成自定义错误呢?
发布于 2020-12-14 00:48:00
最后,我发现我可以从:
response.body?.charStream()所以我创建了第二个方法,如下所示:
fun generateCustomErrorFromReader(code: Int, message:String, stream : Reader?):CustomError {
return try {
val gson = Gson()
val myError: CustomError = gson.fromJson(
stream,
CustomError::class.java
)
//because of gson reflection, the code may be null if the response is empty
if (myError.code == null) {
CustomError(null,code,ErrorCodes.UNKNOWN,message,null)
} else {
myError
}
}catch (e: Exception){
CustomError(null,code,ErrorCodes.UNKNOWN,message,null)https://stackoverflow.com/questions/64984249
复制相似问题