使用execute()通过Retrofit获取正文错误响应

时间:2016-04-07 15:53:26

标签: android retrofit2

因此,出于某种原因,我需要像这样执行我的调用:

val result = manager.call.execute()
if (result.isSuccess) {
   //do stuff
} else {
    //handle exeption
}

当我的代码到达else括号result.body()时为空,result.errorBody()的缓冲区内容为0但不是其长度。

但是,这是我从改造中获得的日志:

<-- 400 Bad Request https://cubus-friends-
...
D/OkHttp: {"error":"validation_error","error_description":"No user with that phone number"}
D/OkHttp: <-- END HTTP (81-byte body)  

如何将我的json错误字符串放入代码中的else括号中?

4 个答案:

答案 0 :(得分:4)

根据@ florian-do的建议,Getting JSON from RetrofitError包含答案,请参阅答案末尾的Retrofit2部分。但是,我正在使用kotlin,这一点变化对于获得转换器是必要的:

val a = object : Annotation{}
val converter = Backend.retrofit. //this is for accessing my Retrofit object
        responseBodyConverter<Error>(Error::class.java, arrayOf(a))

答案 1 :(得分:1)

You can create a simple class like this

class ApiError constructor(error: Throwable) {
    var errorMessage = "An error occurred"
    var error = "error"

    init {
        if (error is HttpException) {
            val errorJsonString = error.response()
                                       .errorBody()?.string()
            parsedString = JsonParser().parse(errorJsonString)
            this.error = parsedString.asJsonObject["error"].asString
            this.errorMessage = parsedString.asJsonObject["error_message"].asString
        } else {
            this.errorMessage = error.message ?: this.errorMessage
        }
    }
}

And use it like so

try  { 
    val result = manager.call.execute()
} catch(error: IOException) {
    ApiError(error).errorMessage
}

The advantage of this approach is that you can use ApiError(error).errorMessage anywhere in your code without having to rewrite the parsing logic.

This is all from this blog post (which I wrote).

答案 2 :(得分:0)

如果你想在错误响应到来时获取数据(通常是200以外的响应代码),你可以像在onResponse()方法中那样做:

  if (result.isSuccess) {
  //do stuff
  } else {
  //handle exeption
      val converter = 
      ApiClient.getClient()?.responseBodyConverter<ErrorResponseData>(
                ErrorResponseData::class.java, arrayOfNulls<Annotation>(0))
                        var errorResponse: ErrorResponseData? = null
                            errorResponse = converter?.convert(response.errorBody())
                            if (errorResponse != null) {
                                //TODO: Handle Error case...
                            }
  }

答案 3 :(得分:0)

这是不创建未使用的注释对象实例的最佳方法

responseBodyConverter<Error>(Error::class.java, arrayOfNulls<Annotation>(0))