In order to handle exceptions in Scala, I prefer avoiding basic try
/catch
and benefit from functional thinking with Validation
from Scalaz (similar to Either
type in certain cases).
My application exposes some services. Imagine this method (making no real sense, but good for the concept) in my service layer. It associates a Buyer
(purchaser) with his new Car
and returns the Car
containing this association if all rules are passed with success:
def create(carDTO: CarDTO, buyerDTO: BuyerDTO): Validation[Either[TechnicalFailure, List[CarCreationFailure]], CarDTO]
Explanation: Creating a Car
may lead to one of both exceptions types:
- Technical failures (when databases crashes for instance) wrapping
Throwable
exceptions. - Business failures (custom application's rules preventing from inconsistence, for instance, a
Car
with an illegal status).CarCreationFailure
is one and of course could be extended by moreprecised
failure.
My question is especially focus on client side and deals specifically with more than one potential Business Failure
.
Should the return type Validation[Either[TechnicalFailure, List[CarCreationFailure]], CarDTO]
be replaced by the less cumbersome: ValidationNel[Throwable, CarDTO]
Note here ValidationNel
(accumulating errors/exceptions into a NonEmptyList
).
A drawback would be that a new reader couldn't, at first glance, guess that this method returns either TechnicalFailure
or CarCreationFailure
(subclass of BusinessFailure
so); just a too frightening Throwable
.
He'd be forced to apply a pattern matching on every Throwable
types contained within my application to in order to be sure to not forget anyone... => messy.
What is the cleanest way among those solutions, or maybe...other one?