Skip to content

Commit

Permalink
Provide better error message
Browse files Browse the repository at this point in the history
Provide better error message on failure to construct classes.
  • Loading branch information
mantono committed Apr 6, 2023
1 parent 24f252b commit c357e1c
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 9 deletions.
21 changes: 13 additions & 8 deletions lib/src/main/kotlin/io/nexure/capsule/Capsule.kt
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,13 @@ private constructor(
): Comparable<Dependency> {
private val instance: LazyValue<Any> = LazyValue(constructor)

fun getInstance(): Any = instance()
fun getInstance(): Any {
return try {
instance()
} catch (e: Exception) {
throw DependencyException(key, e)
}
}

override fun toString(): String = key

Expand All @@ -99,12 +105,11 @@ private constructor(
private fun classKey(clazz: Class<*>): String = clazz.canonicalName ?: clazz.descriptorString()

internal class DependencyException(
val clazz: Class<*>,
override val cause: DependencyException? = null
val key: String,
override val cause: Exception? = null
) : Exception() {
override val message: String = if (cause != null) {
"Unable to provide dependency for class $clazz: \n\t${cause.message}"
} else {
"Unable to provide dependency for class $clazz"
}
constructor(clazz: Class<*>, cause: Exception? = null) : this(classKey(clazz), cause)

override val message: String = "Unable to provide dependency for class ${rootKey()}"
fun rootKey(): String = if (this.cause is DependencyException) this.cause.key else this.key
}
21 changes: 20 additions & 1 deletion lib/src/test/kotlin/io/nexure/capsule/CapsuleTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package io.nexure.capsule
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue

class CapsuleTest {
@Test
Expand Down Expand Up @@ -162,7 +163,6 @@ class CapsuleTest {
assertEquals(listOf("3", "2", "1"), third.getMany<Greeter>().map { it.hello() })
}


@Test
fun `test only needed dependency in created on call to get()`() {
val parent = Capsule {
Expand All @@ -182,6 +182,25 @@ class CapsuleTest {
val greeter: Greeter = child.get()
assertEquals("foo", greeter.hello())
}

@Test
fun `DependencyException should provide context on which class creation that failed`() {
class ComplexGreeter(
val string: String,
val double: Double
) : Greeter {
override fun hello(): String = "foo"
}

val capsule = Capsule {}
try {
val g = capsule.get<ComplexGreeter>()
assertTrue(false)
} catch (e: DependencyException) {
assertEquals("double", e.rootKey())
assertEquals("Unable to provide dependency for class double", e.message)
}
}
}

interface Greeter {
Expand Down

0 comments on commit c357e1c

Please sign in to comment.