Skip to content

Commit e7ea2ad

Browse files
committed
Merge pull request android-async-http#50 from tomwhipple/json-error-content
Support JSON body for non-200 responses
2 parents e15fc1b + 1dd3e6c commit e7ea2ad

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

src/com/loopj/android/http/JsonHttpResponseHandler.java

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,4 +80,29 @@ protected void handleSuccessMessage(String responseBody) {
8080
protected Object parseResponse(String responseBody) throws JSONException {
8181
return new JSONTokener(responseBody).nextValue();
8282
}
83+
84+
/**
85+
* Handle cases where a failure is returned as JSON
86+
*/
87+
public void onFailure(Throwable e, JSONObject errorResponse) {}
88+
public void onFailure(Throwable e, JSONArray errorResponse) {}
89+
90+
@Override
91+
protected void handleFailureMessage(Throwable e, String responseBody) {
92+
super.handleFailureMessage(e, responseBody);
93+
if (responseBody != null) try {
94+
Object jsonResponse = parseResponse(responseBody);
95+
if(jsonResponse instanceof JSONObject) {
96+
onFailure(e, (JSONObject)jsonResponse);
97+
} else if(jsonResponse instanceof JSONArray) {
98+
onFailure(e, (JSONArray)jsonResponse);
99+
}
100+
}
101+
catch(JSONException ex) {
102+
onFailure(e, responseBody);
103+
}
104+
else {
105+
onFailure(e, "");
106+
}
107+
}
83108
}

0 commit comments

Comments
 (0)