Retrofit 2 - Response body null when response status is 422 (unprocessable entity)

前端 未结 3 1440
野性不改
野性不改 2021-02-19 02:37

I\'m using Retrofit to make a POST Request in my web server.

However, I can\'t seem to get the response body when the response status is 422 (unprocessable entit

3条回答
  •  爱一瞬间的悲伤
    2021-02-19 03:06

    Well in this case you'll have to convert the response. Have a look at this link

    All the steps are already provided in the link above.

    For Kotlin users here is the code solution.

    ErrorResponse.kt (This obviously depends on your error response)

    import com.squareup.moshi.Json
    
    data class ErrorResponse(
    
    @Json(name="name")
    val name: String? = null,
    
    @Json(name="message")
    val message: String? = null,
    
    @Json(name="errors")
    val errors: Errors? = null,
    
    @Json(name="statusCode")
    val statusCode: Int? = null
    )
    

    ApiFactory.kt (Let me know if you need the entire code)

    fun parseError(response: Response<*>): ErrorResponse {
        val converter = ApiFactory.retrofit()
                .responseBodyConverter(
                        ErrorResponse::class.java, arrayOfNulls(0)
                )
    
        val error: ErrorResponse
    
        try {
            error = converter.convert(response.errorBody()!!)!!
        } catch (e: IOException) {
            e.printStackTrace()
            return ErrorResponse()
        }
    
        return error
    }
    

    and in the Presenter (I use MVP)

    GlobalScope.launch(Dispatchers.Main) {
            try {
                val response = ApiFactory.apiService.LOGIN(username, password)
                        .await()
                val body = response.body()
                body?.let {
                // Handle success or any other stuff
                    if (it.statusCode == 200) {
                        mView.onSuccess(it.data!!)
                    }
                } ?:
                // This is the else part where your body is null
                // Here is how you use it.
                // Pass the response for error handling
                mView.showMessage(ApiFactory.parseError(response).message!!)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    

    And thats how you roll it! That's All Folks!

提交回复
热议问题