Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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();
}
};
}
}
@krusevdespark
Copy link

krusevdespark commented Dec 25, 2015

how do we use it?

@easycheese
Copy link

easycheese commented Apr 5, 2016

No such method fromResponseBody()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment