简体   繁体   中英

Should I use Try as return type in Scala services?

I'm creating services in Scala just like in Java:

trait PersonService {
  def getById(id: Long): Person 
  def getAll: Iterable[Person]
}

and also I have corresponding implementation of this service.

Actually this service interacts with DB layer and do some business logic. So this methods can throw exceptions.

So I have a question: Should I wrap return type of methods of service with Try ?

Ie should I use following declaration:

trait PersonService {
  def getById(id: Long): Try[Person] 
  def getAll: Try[Iterable[Person]]
}

It depends on whether the error produced by the service is meaningful to the consumer. Ie are they expected to know about the different DB failures and potentially retry? Or are you mapping the exceptions to a consumer meaningful instance? In both of those cases, I would use a Try[Person]

If all you end up is logging the error and you are just trying to avoid, I'd recommend logging in PersonService and returning an Option[Persons] .

Alternatively, if you do want to communicate some information to distinguish failure from empty that does not rise to the level of exception, consider using an Either[FailureReason,Person]

You have 4 standard options:

  1. Future : This might be the most idiomatic and flexible, allowing the consumer to more easily use the service asynchronously and to deal with errors (by matching with Failure ).

  2. Try : A Try signals to the consumer that operations may fail, and that they should be prepared to deal with its exceptions.

  3. Either : You can use an Either similarly to a Try here, but with more customized error information (eg Either[ErrorType, ReturnType] ).

  4. Option : The simplest option here is Option , whereby you ignore the reason for the error and only return Some if the operation was successful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM