Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[values4k] allow custom error messages #60

Open
wants to merge 3 commits into
base: trunk
Choose a base branch
from

Conversation

MarcusDunn
Copy link
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