Skip to content

Commit

Permalink
fix: Better logging when JSON cannot be parsed (#1106)
Browse files Browse the repository at this point in the history
  • Loading branch information
antusus committed Sep 28, 2022
1 parent f513662 commit 5e66ef8
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/main/java/com/box/sdk/BoxJSONResponse.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.eclipsesource.json.Json;
import com.eclipsesource.json.JsonObject;
import com.eclipsesource.json.ParseException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
Expand Down Expand Up @@ -85,7 +86,11 @@ public String getJSON() {
throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e);
}
String jsonAsString = builder.toString();
this.jsonObject = Json.parse(jsonAsString).asObject();
try {
this.jsonObject = Json.parse(jsonAsString).asObject();
} catch (ParseException e) {
throw new RuntimeException("Error parsing JSON:\n" + jsonAsString, e);
}
return jsonAsString;
}
}
Expand Down
45 changes: 45 additions & 0 deletions src/test/java/com/box/sdk/BoxJSONResponseTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package com.box.sdk;

import static java.nio.charset.StandardCharsets.UTF_8;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;

import com.eclipsesource.json.ParseException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import org.junit.Test;

public class BoxJSONResponseTest {

@Test
public void whenJsonCannotBeParseJsonIsInException() throws IOException {
HttpURLConnection mockedConnection = mock(HttpURLConnection.class);
InputStream inputStream = new ByteArrayInputStream("Not a Json".getBytes(UTF_8));
doReturn(200).when(mockedConnection).getResponseCode();
doReturn(inputStream).when(mockedConnection).getInputStream();
try {
new BoxJSONResponse(mockedConnection).getJSON();
} catch (Exception e) {
assertThat(e.getMessage(), is("Error parsing JSON:\nNot a Json"));
assertThat(e.getCause().getClass(), is(ParseException.class));
}
}

@Test
public void whenOtherExceptionIsThrownItIsRethrown() throws IOException {
HttpURLConnection mockedConnection = mock(HttpURLConnection.class);
doReturn(200).when(mockedConnection).getResponseCode();
doThrow(new RuntimeException("Some random exception")).when(mockedConnection).getInputStream();
try {
new BoxJSONResponse(mockedConnection).getJSON();
} catch (Exception e) {
assertThat(e.getMessage(), is("Some random exception"));
assertThat(e.getClass(), is(RuntimeException.class));
}
}
}

0 comments on commit 5e66ef8

Please sign in to comment.