Skip to content

Instantly share code, notes, and snippets.

@bskim45
Forked from felipecsl/ExceptionParser.java
Created July 18, 2016 09:43
Show Gist options
  • Save bskim45/787f2c1b8592d6e37435c7af04d8e69e to your computer and use it in GitHub Desktop.
Save bskim45/787f2c1b8592d6e37435c7af04d8e69e to your computer and use it in GitHub Desktop.
Helper class to parse error response body on Retrofit 2
public static class ExceptionParser {
private final ResponseBody body;
private final String bodyString;
private final Converter.Factory converterFactory;
public ExceptionParser(Response response, Converter.Factory converterFactory) {
this.converterFactory = converterFactory;
this.body = cloneResponseBody(response.errorBody());
this.bodyString = getBodyAsString(body);
}
public <T> T getBodyAs(Type type) {
if (body == null) {
return null;
}
try {
//noinspection unchecked
return (T) converterFactory.fromResponseBody(type, new Annotation[0]).convert(body);
} catch (JsonProcessingException e) {
Log.e(TAG, "Failed to parse error response as JSON", e);
return null;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public String getBodyAsString() {
return bodyString;
}
@Nullable
private static String getBodyAsString(@Nullable ResponseBody responseBody) {
if (responseBody == null) {
return null;
}
try {
return responseBody.string();
} catch (IOException e) {
Log.w(TAG, "Failed to read error ResponseBody as String");
return null;
}
}
@Nullable
private static ResponseBody cloneResponseBody(@Nullable final ResponseBody body) {
if (body == null) {
return null;
}
final Buffer buffer = new Buffer();
try {
BufferedSource source = body.source();
buffer.writeAll(source);
source.close();
} catch (IOException e) {
Log.w(TAG, "Failed to clone ResponseBody");
return null;
}
return new ResponseBody() {
@Override
public MediaType contentType() {
return body.contentType();
}
@Override
public long contentLength() {
return buffer.size();
}
@Override
public BufferedSource source() {
return buffer.clone();
}
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment