Clarify error for non-null Kotlin properties. (#376)

Instead of throwing an InvocationTargetException.
This commit is contained in:
Eric Cochran
2018-01-07 11:07:56 -08:00
committed by Jesse Wilson
parent a210d89a55
commit d2ef4b5a61
2 changed files with 36 additions and 1 deletions

View File

@@ -81,6 +81,9 @@ internal class KotlinJsonAdapter<T>(
"Required value ${constructor.parameters[i].name} missing at ${reader.path}")
}
values[i] = null // Replace absent with null.
} else if (values[i] == null && !constructor.parameters[i].type.isMarkedNullable) {
throw JsonDataException("Non-null value ${constructor.parameters[i].name} " +
"was null at ${reader.path}")
}
}
@@ -89,7 +92,13 @@ internal class KotlinJsonAdapter<T>(
// Set remaining properties.
for (i in constructorSize until bindings.size) {
bindings[i]!!.set(result, values[i])
val binding = bindings[i]!!
val value = values[i]
if (value == null && !binding.property.returnType.isMarkedNullable) {
throw JsonDataException("Non-null value ${binding.property.name} " +
"was null at ${reader.path}")
}
binding.set(result, value)
}
return result

View File

@@ -133,6 +133,32 @@ class KotlinJsonAdapterTest {
class RequiredValueAbsent(var a: Int = 3, var b: Int)
@Test fun nonNullConstructorParameterCalledWithNullFailsWithJsonDataException() {
class Data(val a: String)
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
val jsonAdapter = moshi.adapter(Data::class.java)
try {
jsonAdapter.fromJson("{\"a\":null}")
fail()
} catch (expected: JsonDataException) {
assertThat(expected).hasMessage("Non-null value a was null at \$")
}
}
@Test fun nonNullPropertySetToNullFailsWithJsonDataException() {
class Data { var a: String = "" }
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
val jsonAdapter = moshi.adapter(Data::class.java)
try {
jsonAdapter.fromJson("{\"a\":null}")
fail()
} catch (expected: JsonDataException) {
assertThat(expected).hasMessage("Non-null value a was null at \$")
}
}
@Test fun duplicatedValue() {
val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
val jsonAdapter = moshi.adapter(DuplicateValue::class.java)