Last active
January 28, 2019 12:42
-
-
Save felipecsl/fd03e771e3058f2b2bd6 to your computer and use it in GitHub Desktop.
Helper class to parse error response body on Retrofit 2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
No such method fromResponseBody()