Point at the offending name when failing on unknown

This commit is contained in:
Jake Wharton
2019-09-26 20:36:31 -04:00
parent 86736461c6
commit 12d37ffdc3
4 changed files with 23 additions and 3 deletions

View File

@@ -586,7 +586,10 @@ final class JsonUtf8Reader extends JsonReader {
@Override public void skipName() throws IOException { @Override public void skipName() throws IOException {
if (failOnUnknown) { if (failOnUnknown) {
throw new JsonDataException("Cannot skip unexpected " + peek() + " at " + getPath()); // Capture the peeked value before nextName() since it will reset its value.
Token peeked = peek();
nextName(); // Move the path forward onto the offending name.
throw new JsonDataException("Cannot skip unexpected " + peeked + " at " + getPath());
} }
int p = peeked; int p = peeked;
if (p == PEEKED_NONE) { if (p == PEEKED_NONE) {

View File

@@ -167,7 +167,10 @@ final class JsonValueReader extends JsonReader {
@Override public void skipName() throws IOException { @Override public void skipName() throws IOException {
if (failOnUnknown) { if (failOnUnknown) {
throw new JsonDataException("Cannot skip unexpected " + peek() + " at " + getPath()); // Capture the peeked value before nextName() since it will reset its value.
Token peeked = peek();
nextName(); // Move the path forward onto the offending name.
throw new JsonDataException("Cannot skip unexpected " + peeked + " at " + getPath());
} }
Map.Entry<?, ?> peeked = require(Map.Entry.class, Token.NAME); Map.Entry<?, ?> peeked = require(Map.Entry.class, Token.NAME);

View File

@@ -972,6 +972,20 @@ public final class JsonReaderTest {
reader.endObject(); reader.endObject();
} }
@Test public void skipNameFailUnknown() throws IOException {
JsonReader reader = newReader("{\"a\":1,\"b\":2}");
reader.setFailOnUnknown(true);
reader.beginObject();
assertEquals("a", reader.nextName());
assertEquals(1, reader.nextInt());
try {
reader.skipName();
fail();
} catch (JsonDataException e) {
assertThat(e).hasMessage("Cannot skip unexpected NAME at $.b");
}
}
@Test public void skipNameOnValueFails() throws IOException { @Test public void skipNameOnValueFails() throws IOException {
JsonReader reader = newReader("1"); JsonReader reader = newReader("1");
try { try {

View File

@@ -925,7 +925,7 @@ public final class MoshiTest {
adapter.fromJson("{\"diameter\":5,\"crust\":\"thick\",\"extraCheese\":true}"); adapter.fromJson("{\"diameter\":5,\"crust\":\"thick\",\"extraCheese\":true}");
fail(); fail();
} catch (JsonDataException expected) { } catch (JsonDataException expected) {
assertThat(expected).hasMessage("Cannot skip unexpected NAME at $.diameter"); assertThat(expected).hasMessage("Cannot skip unexpected NAME at $.crust");
} }
} }