Android 无法在改装的错误正文中获取错误响应
我无法在改装的错误主体中获得400响应。我已经设置了日志记录级别,它显示在日志中,但没有显示在错误体中。我搜索了很多次,但没有找到任何解决方案。在这种情况下,有人帮助我解决这个问题吗Android 无法在改装的错误正文中获取错误响应,android,kotlin,retrofit,retrofit2,okhttp,Android,Kotlin,Retrofit,Retrofit2,Okhttp,我无法在改装的错误主体中获得400响应。我已经设置了日志记录级别,它显示在日志中,但没有显示在错误体中。我搜索了很多次,但没有找到任何解决方案。在这种情况下,有人帮助我解决这个问题吗 call_.enqueue(object : Callback<ResponseBody> { override fun onResponse(call: Call<ResponseBody>?, response: Response<ResponseBody&
call_.enqueue(object : Callback<ResponseBody> {
override fun onResponse(call: Call<ResponseBody>?, response: Response<ResponseBody>?) {
if (response?.code() == 400) {
var jObjError: JSONObject? = null
try {
var jObjErrorr = response.errorBody().string()
CustomLogs.displayLogs("$TAG jObjErrorr: $jObjErrorr")
} catch (e: Exception) {
}
try {
val string = jObjError?.getstring("error_description")
CustomLogs.displayLogs("$TAG jObjError: $string")
} catch (e: Exception) {
e.printStackTrace();
}
}
}
但是错误主体并没有显示这个对象,正如IntelliJ Amiya在您的原始帖子的评论中提到的,您应该在
onFailure
方法中执行此操作。据我所知,如果响应代码不在200范围内(200、201、202等),则不会调用改装的onResponse
,因此,如果(response?.code()==400)将永远不会返回真值。决定将其作为单独的答案添加:
if (response?.code() == 400) {
var jObjError: JSONObject? = null
try {
jObjError = response.errorBody().string()
CustomLogs.displayLogs("$TAG jObjError: $jObjError")
} catch (e: Exception) {
}
try {
val string = jObjError?.optString("error_description")
CustomLogs.displayLogs("$TAG jObjError: $string")
} catch (e: Exception) {
e.printStackTrace();
}
}
您能尝试一下这个片段吗?如果您查看改装onResponse库…,它清楚地提到改装不会创建状态代码低于200或高于300的响应主体。您必须专门指定错误响应 您应该使用
onFailure
methodIt's not going onFailure只需重新检查onResponse正在处理什么。我是不对的。对不起。HTTP响应可能仍然指示应用程序级故障,如404或500。其返回值为true。。。它正在进行,并给出了刚才提到的400个代码拼写错误:var jObjError=response.errorBody().string(),您正在调用jObjError?.getstring(“错误描述”)。“jObjError”和“jObjError”。这不是您的问题吗?您正在创建可为空的jObjError变量,并且在try-catch块中,您正在将errorbody添加到您正在创建的不同对象jObjError。然后您尝试从第一个仍然为空的对象获取字符串。欢迎!最好包括文档的链接,并将相关段落复制到您的答案中,并将其格式化为报价。
if (response?.code() == 400) {
var jObjError: JSONObject? = null
try {
jObjError = response.errorBody().string()
CustomLogs.displayLogs("$TAG jObjError: $jObjError")
} catch (e: Exception) {
}
try {
val string = jObjError?.optString("error_description")
CustomLogs.displayLogs("$TAG jObjError: $string")
} catch (e: Exception) {
e.printStackTrace();
}
}