Try with exception logging

后端 未结 4 1502
鱼传尺愫
鱼传尺愫 2020-12-28 15:35

Scala\'s Try is very useful.

I\'d like to use that pattern, but log all exceptions.

How can I do this?

4条回答
  •  有刺的猬
    2020-12-28 16:05

    Starting Scala 2.13, the chaining operation tap can be used to apply a side effect (in this case some logging) on any value while returning the original value:

    import util.chaining._
    
    val x = Try("aa".toInt).tap(_.failed.foreach(println))
    // java.lang.NumberFormatException: For input string: "aa"
    // x: Try[Int] = Failure(java.lang.NumberFormatException: For input string: "aa")
    

    Or an equivalent pattern matching version:

    val x = Try("aa".toInt).tap { case Failure(e) => println(e) case _ => }
    // java.lang.NumberFormatException: For input string: "aa"
    // x: Try[Int] = Failure(java.lang.NumberFormatException: For input string: "aa")
    

    The tap chaining operation applies a side effect (in this case println or some logging) on a value (in this case a Try) while returning the original unmodified value on which tap is applied (the Try):

    def tap[U](f: (A) => U): A

提交回复
热议问题