diff --git a/src/main/java/com/box/sdk/BoxJSONResponse.java b/src/main/java/com/box/sdk/BoxJSONResponse.java index 5ed543c7d..c2060c398 100644 --- a/src/main/java/com/box/sdk/BoxJSONResponse.java +++ b/src/main/java/com/box/sdk/BoxJSONResponse.java @@ -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; @@ -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; } } diff --git a/src/test/java/com/box/sdk/BoxJSONResponseTest.java b/src/test/java/com/box/sdk/BoxJSONResponseTest.java new file mode 100644 index 000000000..cebe28759 --- /dev/null +++ b/src/test/java/com/box/sdk/BoxJSONResponseTest.java @@ -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)); + } + } +}