Skip to content

Instantly share code, notes, and snippets.

@felipecsl
Last active January 28, 2019 12:42
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save felipecsl/fd03e771e3058f2b2bd6 to your computer and use it in GitHub Desktop.
Save felipecsl/fd03e771e3058f2b2bd6 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();
}
};
}
}
@krusevdespark
Copy link

how do we use it?

@easycheese
Copy link

No such method fromResponseBody()

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