square / moshi

A modern JSON library for Kotlin and Java.
https://square.github.io/moshi/1.x/
Apache License 2.0
9.78k stars 761 forks source link

`JsonAdapter.fromJson` functions are documented as throwing `IOException` but actually throw `JsonDataException` #1885

Open Orbar opened 2 months ago

Orbar commented 2 months ago

JsonAdapter.fromJson function are annotated with @Throws(IOException::class) indicating that is the exception that they will throw when there is an error when deserializing a json string, however what is actually thrown is a JsonDataException which is a RuntimeException meaning that if you try to catch the document IOException, your error handling code will be skipped.

For example, consider the following code

@JsonClass(generateAdapter = true)
data class MyType(@Json(name = "one") override val param: String)

...

try {
  myTypeAdapter.fromJson("{}") // just an empty json
catch (e: IOException) {
  // exception will not be caught
}

JsonDataException should extend IOException, or JsonAdapter.fromJson should be updated to indicate that they throw JsonDataException

JakeWharton commented 2 months ago

The exception list is not exhaustive. IOException is declared because it is a checked exception for Java callers.