统一Retrofit失败的处理情况


import android.content.Context;
import android.widget.Toast;

import java.io.IOException;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by xiaolei on 2017/3/2.
 */

public abstract class ICallBack implements Callback
{
    private Context context;
    public ICallBack(Context context)
    {
        this.context = context;
    }
    public abstract void onSuccess(T result) throws Exception;
    public abstract void onField(Call call, Throwable t);
    public abstract void onFinally();
    
    @Override
    public void onResponse(Call call, Response response)
    {
        try
        {
            if(response.isSuccessful())
            {
                onSuccess(response.body());
            }else
            {
                onFailure(call,new IOException(response.code()+""));
            }
        }catch (Exception e)
        {
            onFailure(call,new IOException(response.code()+""));
        }finally
        {
            onFinally();
        }
    }

    @Override
    public void onFailure(Call call, Throwable t)
    {
        try
        {
            if(context != null)
            {
                Toast.makeText(context, "t:" + t, Toast.LENGTH_SHORT).show();
            }
            onField(call,t);
        }finally
        {
            onFinally();
        }
    }
}

你可能感兴趣的:(统一Retrofit失败的处理情况)