简体   繁体   中英

How to handle null or empty responses using retrofit

From the server, sometimes we are getting a response that is null or empty. Because of this, our code will crash at some null pointer exception. We don't want to have null checks everywhere in code. Is there a way to specify default values when a retrofit response is null or empty? In the code below, this is how we can handle it on a case-by-case basis. But, we do not want to write this logic for every object. We want to do this somehow at the application level. Is that possible?

@SerializedName("isPdf")
@Expose
private String isPdf;


public boolean getIsPdf() {
    return !Util.isNullOrEmpty(isPdf) && isPdf.equalsIgnoreCase("true") ? true : false;
}

public void setIsPDF(boolean isPdf) {

    this.isPdf = isPdf ? "true" : "false";
}

You can create a default callback that handles a null response the way you want. For example, calling onFailure :

public class DefaultCallback<T> implements Callback<T> {

    private static final String TAG = "YOUR_TAG";
    private Callback<T> callback;

    public DefaultCallback(Callback<T> callback) {
        this.callback = callback;
    }

    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        if (response.body() == null) {
            callback.onFailure(call, new NullPointerException("Empty response"));
        } else {
            callback.onResponse(call, response);
        }
    }

    @Override
    public void onFailure(Call<T> call, Throwable t) {
        Log.e(TAG, t.toString());
        callback.onFailure(call, t);
    }
}

And then use this callback in your implementation.

Call<MyObject> call = ... //Create your call
call.enqueue(new DefaultCallback<>(new Callback<MyObject>() {
    @Override
    public void onResponse(Call<MyObject> call, Response<MyObject> response) {
        //Handle successful non-null responses
    }

    @Override
    public void onFailure(Call<MyObject> call, Throwable t) {
        //Handle errors/null responses
    }
}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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