Skip to content

Commit f8314f5

Browse files
committed
handle non-json error entities from server
1 parent 762e454 commit f8314f5

File tree

1 file changed

+23
-9
lines changed

1 file changed

+23
-9
lines changed

intercom-java/src/main/java/io/intercom/api/HttpClient.java

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
import java.util.ArrayList;
2121
import java.util.HashMap;
2222
import java.util.Map;
23+
import java.util.concurrent.ThreadLocalRandom;
2324

2425
class HttpClient {
2526

@@ -149,8 +150,15 @@ private <T> T runRequest(URI uri, Class<T> response, HttpURLConnection conn) thr
149150
}
150151

151152
private <T> T handleError(URI uri, HttpURLConnection conn, int responseCode) throws IOException {
152-
final ErrorCollection errors = objectMapper.readValue(conn.getErrorStream(), ErrorCollection.class);
153-
logError(uri, responseCode, errors);
153+
ErrorCollection errors;
154+
try {
155+
errors = objectMapper.readValue(conn.getErrorStream(), ErrorCollection.class);
156+
} catch (IOException e) {
157+
errors = createUnprocessableErrorResponse(e);
158+
}
159+
if (logger.isDebugEnabled()) {
160+
logger.debug("error json follows --\n{}\n-- ", objectMapper.writeValueAsString(errors));
161+
}
154162
return throwException(responseCode, errors);
155163
}
156164

@@ -162,13 +170,6 @@ private <T> T handleSuccess(Class<T> response, HttpURLConnection conn, int respo
162170
}
163171
}
164172

165-
private void logError(URI uri, int responseCode, ErrorCollection errors) throws JsonProcessingException {
166-
logger.info("[{}] returned [{}] [{}]", uri.toASCIIString(), responseCode, errors);
167-
if (logger.isDebugEnabled()) {
168-
logger.debug("api error json follows --\n{}\n-- ", objectMapper.writeValueAsString(errors));
169-
}
170-
}
171-
172173
private <T> T readEntity(HttpURLConnection conn, int responseCode, Class<T> entityType) throws IOException {
173174
final InputStream entityStream = conn.getInputStream();
174175
try {
@@ -239,5 +240,18 @@ private Map<String, String> createHeaders() {
239240
return headers;
240241
}
241242

243+
private ErrorCollection createUnprocessableErrorResponse(IOException e) {
244+
ErrorCollection errors;
245+
final long grepCode = getGrepCode();
246+
final String msg = String.format("could not parse error response: [%s]", e.getLocalizedMessage());
247+
logger.error(String.format("[%016x] %s", grepCode, msg), e);
248+
Error err = new Error("unprocessable_entity", String.format("%s logged with code [%016x]", msg, grepCode)) ;
249+
errors = new ErrorCollection(Lists.newArrayList(err));
250+
return errors;
251+
}
252+
253+
private long getGrepCode() {
254+
return ThreadLocalRandom.current().nextLong();
255+
}
242256

243257
}

0 commit comments

Comments
 (0)