Skip to content

[values4k] allow custom error messages#60

Open
MarcusDunn wants to merge 3 commits intofork-handles:trunkfrom
MarcusDunn:47-customer-error-message
Open

[values4k] allow custom error messages#60
MarcusDunn wants to merge 3 commits intofork-handles:trunkfrom
MarcusDunn:47-customer-error-message

Conversation

@MarcusDunn
Copy link
Copy Markdown
Contributor

Fix for #47 (by overriding to a transparent error handler) but also allows for better messages by including the failed value (either on the parse or the validate). The default behavior remains unchanged.

Example

class MyIntValue private constructor(value: Int) : IntValue(value) {
    companion object : IntValueFactory<MyIntValue>(::MyIntValue, { it > 0 },
        onInvalid = { value, e -> throw IllegalArgumentException("Value ($value) must be greater than 0", e) },
        onParseFailure = { value, e -> throw IllegalArgumentException("Value ($value) must be an integer", e) }
    )
}
@Test
fun customOnInvalid() {
    val exception = assertThrows<IllegalArgumentException> {
        MyIntValue.parse("-1")
    }
    assertThat(exception.message, equalTo("Value (-1) must be greater than 0"))
}

@Test
fun customOnFailedParse() {
    val exception = assertThrows<IllegalArgumentException> {
        MyIntValue.parse("cat")
    }
    assertThat(exception.message, equalTo("Value (cat) must be an integer"))
}

Alternatives include:

only one onFailure handler which does not contain the String (if parsing) or the PRIMATIVE (if validating).

I prefer having access to the value that caused the exception (but it would fix #47)

transparently throw an error every time (this allows custom error messages when parsing) and allow some sort of onInvalid to be customized (allowing custom error messages on validation)

This would be a breaking change, but otherwise is much simpler.

keep current behavior, do not allow overriding
no fix for #47, but keeps code smaller and simpler.

@MarcusDunn MarcusDunn changed the title allow custom error messages [values4k] allow custom error messages Apr 3, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[values4k] Forced message in factory

1 participant