Scala - 尝试使用异常记录 [英] Scala - Try with exception logging

查看:150
本文介绍了Scala - 尝试使用异常记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Scala的尝试非常有用。我想使用该模式,但记录所有异常。如何做到这一点?

Scala's Try is very useful. I'd like to use that pattern, but log all exceptions. How can I do this?

推荐答案

定义以下帮助器:

import scala.util.{Try, Failure}

def LogTry[A](computation: => A): Try[A] = {
  Try(computation) recoverWith {
    case e: Throwable =>
      log(e)
      new Failure(e)
  }
}

然后你可以使用它,因为你将使用尝试,但任何异常将通过 log(e)

Then you can use it as you would use Try, but any exception will be logged through log(e).

这篇关于Scala - 尝试使用异常记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆