Skip to content

KotlinJsonAdapter wraps init block exceptions in InvocationTargetException #692

@BenTilbrook

Description

@BenTilbrook

When using KotlinJsonAdapterFactory, if your data class throws an exception from its init block, the exception is wrapped in an InvocationTargetException.

This is a very useful technique for providing additional validation, so it's a shame we can't rely on getting that exception without unwrapping it.

Also, this isn't really consistent with Moshi's exception throwing principles. It introduces another arbitrary exception that seems to be just an implementation detail leak.

In addition, the behavior is different from codegen'ed adapters. I'd expect it to be the same.

The following test demonstrates the problem:

class MoshiTest {

    // Fails
    @Test(expected = JsonDataException::class)
    fun test() {
        val moshi = Moshi.Builder()
            .add(KotlinJsonAdapterFactory())
            .build()
        val json = """{
           "yearsOld": -1
        }"""
        moshi.adapter<Age>(Age::class.java).fromJson(json)
    }

    data class Age(val yearsOld: Int) {
        init {
            if (yearsOld < 0) throw JsonDataException()
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions