I\'ve seen many times pieces of scala code using Option (for simple values) or Either[List[Error], T] for handling errors.
this gives place to code like this
As om-nom-nom said, I asked a similar question: Throwing exceptions in Scala, what is the "official rule"
But it's not the only one I asked that may interest you, because I used to code with a lot of boilerplate code and a lot of indentation levels because of pattern matching etc...
You can check these links: Handling failures with Either -> Where is the stacktrace?
Kind of related to error handling too, which may interest you: Method parameters validation in Scala, with for comprehension and monads In which Travis Brown gave a more detailed answer, about using applicative functors and Scalaz to do fail-fast (first error blocks the process) or collection all errors of a suite of operations Same kind of question: Handling fail-fast failures when the return type is Option[Error]
And you can check this link which uses by-name parameters do perform of sequence of operations too. It may be a good alternative to using right projections in a for comprehension, but you can't create intermediare results :( Validation with a sequence of by-name parameters in Scala? I don't know if it can be used with your code exemple but I don't think so in this case (assuming your refreshApplicationToken is free of side effects and return a newly created immutable user instance, instead of mutating a token variable)
The following version uses the fact that the right projection of Either
is a monad, and is exactly equivalent to your code:
def createApplicationToken(accessToken: AccessToken) = for {
info <- retrieveProviderInfo(accessToken).right
user <- User.findOrCreateFromProviderInfo(info).right
refr <- user.refreshApplicationToken.right
} yield refr.token
And does a much better job of showing off the advantages of Either
.
More generally, the rules are the same as in Java: use exceptions for exceptional situations. You just might find that you change your definition of exceptional a bit when you're working in this style—e.g., invalid user input isn't really exceptional, a timed-out network request isn't really exceptional, etc.
Either
since Scala 2.12You can now omit .right
, so the following code is equivalent since Scala 2.12:
def createApplicationToken(accessToken: AccessToken) = for {
info <- retrieveProviderInfo(accessToken)
user <- User.findOrCreateFromProviderInfo(info)
refr <- user.refreshApplicationToken
} yield refr.token
The answer varies between what is ideal and what is practical. Ideally, avoid using exceptions. Practically, you can't live without them.
Scala seems to favor one-liners and along those lines v2.10 has the new monad Try:
import scala.util.Try
def percentCompleted( total:Int, done:Int ): Int = Try (done * 100 / total) getOrElse 100
percentCompleted( 0, 10 ) // Catches divide-by-zero and returns 100% instead