Retrofit在Error回调中添加自定义对象。 onFailure处

时间:2016-08-31 13:21:51

标签: android retrofit retrofit2

您好我正在使用改装我的回调如下

       @Override
public void onResponse(final Call<T> call, Response<T> response) {

    if (response.isSuccessful()) {
       passing this to my view

    } else {


 //      as this failed other then 200      retroCallback.onFailure(call, new Throwable(""));

    }
}

@Override
public void onFailure(Call<T> call, Throwable t) {
    retroCallback.onFailure(call, t);
}

所以在这个我怎么能传递我的ErrorBean而不是Throwable我们可以在onFailure中传递自定义模型?因为我的服务器给了我一些合成的响应我想通过那种格式..我正在使用改造2.1.0

2 个答案:

答案 0 :(得分:1)

您可以使用合成继承Throwable并传递其他对象。

"this is my stringthat"

然后,在onError:

public class ErrorBean extends Throwable {
    public ErrorPayload payload = null;

    public ErrorBean(ErrorPayload payload) {
        this.payload = payload;
    }
}

答案 1 :(得分:0)

AFAIK ,, Retrofit on onFailure用于处理无互联网连接等错误。

要处理来自服务器的错误响应,错误响应,我的意思是来自具有4xx状态代码的服务器的响应,但是客户端有一些JSON响应来处理它。

说,您从服务器获取此错误结构:

{
    statusCode: 409,
    message: "Email address already registered"
}

此错误将在onResponse(...)中捕获。要处理此问题,请创建

public class ErrorBean {

    private int statusCode;
    private String message;

    public ErrorBean() {
    }

    public int status() {
        return statusCode;
    }

    public String message() {
        return message;
    }
}

创建一个简单的ErrorHandler util:

public class ErrorUtils {

    public static ErrorBean parseError(Response<?> response) {
        Converter<ResponseBody, ErrorBean> converter = 
                ServiceGenerator.retrofit()
                        .responseBodyConverter(ErrorBean.class, new Annotation[0]);

        ErrorBean error;

        try {
            error = converter.convert(response.errorBody());
        } catch (IOException e) {
            return new ErrorBean();
        }

        return error;
    }
}

最后,

...
call.enqueue(new Callback<SuccessResponse>() {  
    @Override
    public void onResponse(Call<SuccessResponse> call, Response<SuccessResponse> response) {
        if (response.isSuccessful()) {
            // use response data and do some fancy stuff :)
        } else {
            // parse the response body …
            ErrorBean error = ErrorUtils.parseError(response);
            // … and use it to show error information

            // … or just log the issue like we’re doing :)
            Log.d("error message", error.message());
        }
    }

    @Override
    public void onFailure(Call<User> call, Throwable t) {
        // there is more than just a failing request (like: no internet connection)
    }
});

希望你明白这一点...... !!!