繁体   English   中英

在Retrofit2中显示错误响应的正确方法是什么?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM