If I have some validation function:
def validateOne(a: A): Try[A]
And I now want to validate a collection of A by using the validateOne
function
def validateAll(all: List[A]): Try[List[A]]
Is there a nice way to return a Failure
as soon as the first element is found to be invalid?
The way I'm doing it now is by calling get
after validating each element. For the first element where validateOne
returns Failure
, get
throws the wrapped exception...which I catching re-wrap:
def validateAll(all: List[A]): Try[List[A]] = try {
all.map(a => validateOne(a).get)
} catch {
case e: MyValidationException => Failure(e)
}