I’m working on a function where there is more than one possible failure path that I need to differentiate between. My paths are
- success – return the value
- logical error – non-fatal issue that the can be recovered from
- exception – unexpected error that should be bubbled up
I found the arrow documentation here: https://arrow-kt.io/learn/typed-errors/working-with-typed-errors/ and read through it, but I’m still struggling to understand how to actually apply the information.
If I have some code like the following:
fun doValidation():Either<Error,String>
{
val v1 = "123abc"
val v2 = "abc"
val v3 = "1234"
validateName(v1)
validateName(v2)
validateName(v3)
}
fun validateName( value:String):Either<Error,String>
{
if(value.length < 4)
{
//this is an unexpected exception
return Error("$value has less than 4 characters").left()
}
else if(value.contains("abc"))
{
//this is a logical failure that we can recover from
//this will not compile as-written
return value.left()
}
else
{
return (value + "_xyz").right()
}
}
what is the idiomatic way to implement validateName() such that doValidation can detect and recover from logical errors while still bubbling exceptions up the call stack?