lundi 6 juin 2016

Handling exceptions in Synchronous Retrofit call

I need to handle retrofit exception with my synchronous API method call. I know you can get the errorBody by this way:

    Call<ResponseBody> call = cobaltServices.upload(map);
    Response<ResponseBody> response = call.execute();
    ResponseBody errorBody = response.errorBody();

I'm lost with what to do with the errorBody after. I already read many solutions to handle it but I found most of them confusing, way to complex and not well explained. Here is a method I use:

private String uploadFile(String path, final String type) throws IOException, JSONException {

    String result = null;

    Map<String, RequestBody> map = new HashMap<>();

    Call<ResponseBody> call = cobaltServices.upload(map);
    Response<ResponseBody> response = call.execute();
    ResponseBody errorBody = response.errorBody();
    // TODO Handle errorBody

    if (response != null) {
        JSONObject obj = new JSONObject(response.body().string());
        if (obj != null) {
            if (obj.has("fileid")) {
                settings.edit().putInt(FILE_ID, (int) obj.get("fileid")).commit();
                result = RESULT_OK;
            }
        }
    }
    return result;
}

Aucun commentaire:

Enregistrer un commentaire