Skip to content

Commit cbfb95f

Browse files
committed
Error handling example
1 parent 28e7de3 commit cbfb95f

File tree

1 file changed

+21
-7
lines changed

1 file changed

+21
-7
lines changed
Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,24 @@
11
package freetransformer
22

3+
import freetransformer.Language.{Data, Error}
4+
35
import scala.util.{Failure, Success}
4-
import scalaz.Free
6+
import scalaz._
7+
8+
trait ErrorPolicy {
9+
def error(ex: Throwable): Free[Data, Nothing]
10+
}
511

6-
object Interpreter {
12+
trait GlobalErrorPolicy extends ErrorPolicy {
13+
override def error(ex: Throwable): Free[Data, Nothing] = ex match {
14+
case ex: Exception =>
15+
val e: Free[Data, Nothing] = Free.liftF(Error(ex))
16+
e
17+
}
18+
}
19+
20+
trait Interpreter {
21+
this: ErrorPolicy =>
722

823
import Language._
924
import Logic._
@@ -12,11 +27,8 @@ object Interpreter {
1227
case Read(data, next) =>
1328
val d = core.read(data)
1429
d match {
15-
case Success(value) =>
16-
run(core, next(value))
17-
case Failure(ex) =>
18-
val e: Free[Data, Nothing] = Free.liftF(Error(ex))
19-
run(core, e)
30+
case Success(value) => run(core, next(value))
31+
case Failure(ex) => run(core, error(ex))
2032
}
2133
case CalculateA(_, next) => run(core, next(core))
2234
case CalculateB(_, next) => run(core, next(core))
@@ -25,3 +37,5 @@ object Interpreter {
2537
case Error(ex) => Left(ex.getMessage)
2638
}, (a: A) => Right(a))
2739
}
40+
41+
object Interpreter extends GlobalErrorPolicy

0 commit comments

Comments
 (0)