我正在尝试将错误体从一个异常映射到一个有用的模型中,并使用moshi和retrofit 2.9.0。
我发现了许多讨论相同问题的帖子,但是没有一个解决方案对我有用。
我的代码如下
private fun getErrorMessageFromGenericResponse(httpException: HttpException): String? {
var errorMessage: String? = null
try {
val body = httpException.response()!!.errorBody()!!
val errorResponse = body.string().toObject(ErrorResponse::class.java)
errorMessage = errorResponse?.message
} catch (e: IOException) {
e.printStackTrace()
} finally {
return errorMessage
}
}
fun <T> String.toObject(objectClass: Class<T>): T? {
val moshi = Moshi.Builder().build()
val adapter = moshi.adapter(objectClass).lenient()
return adapter.fromJson(this)
}我也试过使用这个,但它也不起作用:
httpException.response()!!.errorBody()!!.source().buffer.snapshot().utf8()我可能错过了一些非常简单的东西,因为我认为这是一个常见的用法。
提前谢谢。
发布于 2022-01-25 02:53:12
fun handleErrorResponse(e: Throwable): String {
return when (e) {
is HttpException -> {
parseHTTPError(e.response()!!.errorBody())
}
is SocketTimeoutException -> {
ApiConstants.TIME_OUT
}
is IOException -> {
ApiConstants.SERVERERROR
}
else -> ApiConstants.SERVERERROR
}
}
fun parseHTTPError(responseBody: ResponseBody?): String {
try {
val jsonObject=JSONObject(responseBody!!.string())
try {
val error=jsonObject.getJSONArray("message")
return error[0].toString()
} { responseBody!!.close()返回“} responseBody.close()返回”}
https://stackoverflow.com/questions/70841548
复制相似问题