lundi 6 juin 2016

Generalize exception's handling Retrofit

I have multiple API call in my Retrofit service and each methods are handling the same ugly Exceptions and checking the same attribute in the JSON response. I tried to make it more generic to reduce the size of each method but I don't know what's the best way to do it... Here is two of many method that does pretty much the same things but with a different API call:

private void sendStopSecurityCheck() {
    Intent intent = new Intent(STOP_SECURITY_CHECK);
    intent.putExtra(RESULT, RESULT_FAILED);

    boolean isSuccess = connectAmazonApi();

    if(isSuccess){
        Call<ResponseBody> call = amazonServices.stopSecurityCheck(settings.getString("username", ""), settings.getString("orgid", ""));
        try {
            ResponseBody response = call.execute().body();
            JSONObject obj;
            if (response != null) {
                obj = new JSONObject(response.string());
                if(obj.getBoolean("success") == true){
                    intent.putExtra(RESULT, RESULT_OK);
                }
                Log.w(TAG, "Result " + obj.toString());
            }
        } catch (IOException e) {
            Log.w(TAG, "Request failed: " + e.getMessage());
        } catch (JSONException e) {
            Log.w(TAG, "Request failed: " + e.getMessage());
        }
    }else{
        Log.w(TAG, "Impossible to connect to Amazon API");
    }

    sendBroadcast(intent);
}

private void sendConfirmSecurityCheck() {
    Intent intent = new Intent(CONFIRM_SECURITY_CHECK);
    intent.putExtra(RESULT, RESULT_FAILED);

    boolean isSuccess = connectAmazonApi();

    if(isSuccess){
        Call<ResponseBody> call = amazonServices.confirmSecurityCheck(settings.getString("username", ""), settings.getString("orgid", ""));
        try {
            ResponseBody response = call.execute().body();
            JSONObject obj;
            if (response != null) {
                obj = new JSONObject(response.string());
                if(obj.getBoolean("success") == true){
                    intent.putExtra(RESULT, RESULT_OK);
                }
                Log.w(TAG, "Result " + obj.toString());
            }
        } catch (IOException e) {
            Log.w(TAG, "Request failed: " + e.getMessage());
        } catch (JSONException e) {
            Log.w(TAG, "Request failed: " + e.getMessage());
        }
    }else{
        Log.w(TAG, "Impossible to connect to Amazon API");
    }

    sendBroadcast(intent);
}

Aucun commentaire:

Enregistrer un commentaire