Are there problems using Try or Either to handle errors in the Scala open / open source API?

I noticed that many Scala open source APIs use Future(like Slick) or Java-style exception handling (like spray-json) rather than Tryor Either.

Are there problems with reverting, Tryor Eitherin simple open source APIs that are not lengthy or asynchronous? Should I avoid these and, if so, what should I use instead?

(Obviously, I would rather use the basic Scala APIs rather than third-party libraries such as Scalaz, so as not to force downstream users to use these libraries.)

+4
source share
3 answers

TryGreat for wrapping exceptions for non-asynchronous operations.
However, I believe that using an exception instance to return a non-exceptional error condition is incorrect. I also stick to this when the API is asynchronous and uses Future. Mixing exceptional errors with business errors easily leads to incorrect / insufficient error handling by API clients (otherwise me :)).

If you decide to use exceptions to indicate your business mistakes, remember that exceptions have a hidden price: building a stack trace. This can be facilitated if you create your own business exceptions and mix scala.util.control.NoStackTrace.

Either Scala , , :

(), Left ().

"" ( )

(scala 2.11.6 ) API, , Scala.

, Validation. , play-json JsResult . , , .

slip , Scala. 2 , , .

+4

Try [T], : ( ). , :

  • - ( , -).

  • Throwable, , , - .

. , , ! , : . , , : with NoStackTrace, .

def validate(s:String):Try[String] = Option(s).filter(!_.isEmpty).map(Try(_)).getOrElse(new Exception("bad input") with NoStackTrace 

Lither [L, R], : , (.. [Integer, Float]). , , Scalaz , , , .

def parseNum(s:String):Either[Int,String] = Try(parseInt(s)).map(Left(_)).getOrElse(Right(s))

, , N, ( , )

def parseAndReturn(s:String):(Integer,String) = (parseInt(s), s) 

[T], T , , Try [T], *** , .

def attemptToparse(s:String):Option[Result] = Try(parse(s)).toOption
+2

, Try /, /. Scalaz - , , , Either , , IMHO: , , Right , " " .rightProjection ( , . - fold fold[X](fa: (A) ⇒ X, fb: (B) ⇒ X): X myEither.fold(dealWithErrors _, happyPath _ ) ( , dealWithErrors happyPath )

0

All Articles