Implicit class that adds a toOr
method to
Try
, which converts Success
to Good
,
and Failure
to Bad
, as well as a
validation
method, which takes one or more functions that validate
the Future
's value.
Implicit class that adds a toOr
method to
Try
, which converts Success
to Good
,
and Failure
to Bad
, as well as a
validation
method, which takes one or more functions that validate
the Future
's value.
See the main documentation for trait TrySugar
for more detail and examples.
Trait providing an implicit class that adds a
toOr
method toTry
, which convertsSuccess
toGood
, andFailure
toBad
, as well as avalidating
method, which takes one or more validation functions and returns either the sameTry
if either theTry
had already failed or its value passes all the functions, orValidationFailedException
containing an error message describing the first validation that failed.Here's an example validation method, which passes if the given
Int
is evenly divisible by 10 (i.e., the result will bePass
). If the value does not pass this test, the result is aFail
containing a helpful error message string.Validation will be attempted on a successful
Try
. If the validation succeeds, the resultingTry
will be the same successfulTry
with the same value. (A "validation" only transforms theTry
if the validation fails, otherwise it is the sameTry
. The only difference is its value has now been proven valid.) In the following example, a successfulTry[Int]
with the value 100 passes the validation (which checks whether 100 is evenly divisible by 10), therefore the result of thevalidating
call is the same successfulTry
with the same value.If validation fails, the successful
Try
will be transformed into a failed one, with aValidationFailedException
that contains the error message returned by the validation function. In the following example, 42 fails the validation because it is not evenly divisible by 10:If
validating
is called on a failedTry
, it just returns the same failedTry
:The
validating
method accepts one or more validation functions. If you pass more than one, they will be tried in order up until the first failure, whose error message will appear in theValidationFailedException
. In other words,validating
will short circuit at the first error and return that. It will not accumulate errors. For example, the following validation will short circuit after theisDivBy3
function fails:Here are some examples of the
toOr
method: