[英]What is the correct way to show error response in Retrofit2?
我創建了Model類來處理Retrofit2回調:
public class ModelSendPhone {
@Expose
@SerializedName("code")
private int code;
@Expose
@SerializedName("user_id")
private int user_id;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
這是我的通話代碼:
Call<ModelSendCode> sendCodeCall = getRetrofit().sendCode(params);
sendCodeCall.enqueue(this);
現在我注意到,如果我輸入了錯誤的@Params,響應將給我錯誤422和JSON響應正文,並顯示以下消息:
{"name":"Unprocessable entity","message":"Wrong params","code":0,"status":422,"type":"yii\\web\\HttpException"}
我的問題是我應該如何在onResponse方法內的Toast中顯示此“消息”? 我正在實現Callback<ModelSendCode>
我的onResponse方法未對其進行解析。
提前致謝
您的模型可以看起來像這樣,只要檢查狀態即可做出響應。
public class ModelSendPhone implements Serializable
{
private String message;
private String status;
private String name;
private int user_id;
private int code;
private String type;
public String getMessage ()
{
return message;
}
public void setMessage (String message)
{
this.message = message;
}
public String getStatus ()
{
return status;
}
public void setStatus (String status)
{
this.status = status;
}
public String getName ()
{
return name;
}
public void setName (String name)
{
this.name = name;
}
public int getUser_id ()
{
return user_id;
}
public void setUser_id (int user_id)
{
this.user_id = user_id;
}
public int getCode ()
{
return code;
}
public void setCode (int code)
{
this.code = code;
}
public String getType ()
{
return type;
}
public void setType (String type)
{
this.type = type;
}
@Override
public String toString()
{
return "ClassPojo [message = "+message+", status = "+status+", name = "+name+", user_id = "+user_id+", code = "+code+", type = "+type+"]";
}
}
在您的onResponse方法中,您將獲得一個類型的響應對象
Response<ModelSendCode>
這是一個HTTP響應。 根據Square文檔
您只需執行response.message()
即可從HTTP響應中獲取消息。 您還可以使用response.isSucessful()
檢查它是否成功。 你有嘗試過嗎?
感謝您的評論,但我找到了我所需要的。 response.errorBody().string()
根據docs ,這是正確的方法,以獲取對任何錯誤的默認響應,現在我將其轉換為Json並根據需要進行解析
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.