对带有scala的catch块使用分部函数
我有一个catch块,我重复了很多次,发现了这个问题,证实了我可以使用一个部分函数作为catch块(Scala 2.9的try…catch泛化的用例是什么?) 目前,我的代码如下所示:对带有scala的catch块使用分部函数,scala,Scala,我有一个catch块,我重复了很多次,发现了这个问题,证实了我可以使用一个部分函数作为catch块(Scala 2.9的try…catch泛化的用例是什么?) 目前,我的代码如下所示: var task = newTask("update product", "update for customer " + customerId.toString) try { val vcdRouter = actorSystem.actorFor("user/supervisor/rout
var task = newTask("update product", "update for customer " + customerId.toString)
try {
val vcdRouter = actorSystem.actorFor("user/supervisor/router-10.10.10.10:443")
val vdcId = new UUID("92ddba5e-8101-4580-b9a5-e3ee6ea5718f")
val vdcGet = sendExpect[AdminVdcType](vcdRouter, GetVdc(vdcId))
val vdcPut = VdcPutConfig(vdcGet, c)
val vdcPutTask = sendExpect[TaskType](vcdRouter, UpdateVdc(vdcId, vdcPut))
task = task.copy(Progress = 100, status = SuccessType)
} catch {
case failure: NoResponseBodyException =>
logger.debug("*** In putCustomerProduct, got a Left(VcdGatewayException)")
task = task.copy(Progress = 100, status = Error, Error = Option(exceptionToError(failure, BadGateway)))
case failure: VcdGatewayException ⇒
logger.debug("*** In putCustomerProduct, got a Left(VcdGatewayException)")
task = task.copy(Progress = 100, status = Error, Error = Option(exceptionToError(failure, GatewayTimeout)))
case failure: Exception ⇒
logger.debug("*** In putCustomerProduct, got a Left(Exception)")
task = task.copy(Progress = 100, status = Error, Error = Option(exceptionToError(failure)))
}
因为我有一个在catch块内变化的task变量,有没有一种好方法可以从保存catch块的分部函数中访问它?该任务是一个var,因为它在进入系统时设置了一些初始化数据,如创建的时间戳。我可以解决这个问题,但我对原始问题的答案很感兴趣。我对scala很陌生,所以我的答案可能不太正确,但是: 在每个“case”块中,唯一改变的是错误类型。 首先,我将为异常类型创建另一个匹配项。 差不多
def exceptionToErrorReason(val failure:Exception) : ErrorReason = failure.getClass match {
case classOf[NoResponseBodyException] => BadGateway
case classOf[VcdGatewayException ] => GatewayTimeout
case _ => null
}
现在你可以像这样改变你的挡块
case failure: Exception ⇒
logger.debug("*** In putCustomerProduct, got a Left(" + failure.getClass().getSimpleName() + )")
task = task.copy(Progress = 100, status = Error, Error = Option(exceptionToError(exceptionToErrorReason(failure)))
剩下的就省去了。无需复制任何内容。我假设您有几个不同的函数,它们具有不同的
var任务
s,您希望使用它们
您可以创建一个函数,该函数同时使用任务
和任务设置器作为参数,它返回一个部分函数
,您可以将其用作捕获处理程序
def handler(task: Task, setTask: Task => Any): PartialFunction[Throwable, Any] = {
case failure: NoResponseBodyException =>
logger.debug("*** In putCustomerProduct, got a Left(NoResponseBodyException)")
setTask(task.copy(Progress = 100, status = Error, Error = Option(exceptionToError(failure, BadGateway))))
case failure: VcdGatewayException =>
logger.debug("*** In putCustomerProduct, got a Left(VcdGatewayException)")
setTask(task.copy(Progress = 100, status = Error, Error = Option(exceptionToError(failure, GatewayTimeout))))
case failure: Exception =>
logger.debug("*** In putCustomerProduct, got a Left(Exception)")
setTask(task.copy(Progress = 100, status = Error, Error = Option(exceptionToError(failure))))
}
// somewhere else in your code...
var task = newTask("update product", "update for customer " + customerId.toString)
try {
val vcdRouter = actorSystem.actorFor("user/supervisor/router-10.10.10.10:443")
val vdcId = new UUID("92ddba5e-8101-4580-b9a5-e3ee6ea5718f")
val vdcGet = sendExpect[AdminVdcType](vcdRouter, GetVdc(vdcId))
val vdcPut = VdcPutConfig(vdcGet, c)
val vdcPutTask = sendExpect[TaskType](vcdRouter, UpdateVdc(vdcId, vdcPut))
task = task.copy(Progress = 100, status = SuccessType)
} catch handler(task, task = _)
我也同意您应该尝试减少catch处理程序中的重复。这里是使用
scala.util.control.Exception
的另一种方法
scala> import util.control.Exception._
import util.control.Exception._
首先创建Catch[\u]
对象来处理特定的异常
scala> val nfeh = handling(classOf[NumberFormatException]) by println
nfeh: util.control.Exception.Catch[Unit] = Catch()
scala> val aobeh = handling(classOf[ArrayIndexOutOfBoundsException]) by println
aobeh: util.control.Exception.Catch[Unit] = Catch()
使用或方法将它们组合在一起。请注意,就像在catch
块中一样,顺序很重要
scala> val h = nfeh or aobeh
h: util.control.Exception.Catch[Unit] = Catch()
将处理程序应用于可能引发异常的代码
scala> h apply {
| println("1o2".toInt)
| }
java.lang.NumberFormatException: For input string: "1o2"
scala> h apply {
| val x = Array(8)
| println(x(2))
| }
java.lang.ArrayIndexOutOfBoundsException: 2
至于任务
部分,您可以按照以下思路进行操作:
scala> val nfeh = handling(classOf[NumberFormatException]) by { ex =>
| println(ex)
| -1
| }
nfeh: util.control.Exception.Catch[Int] = Catch()
scala> val aobeh = handling(classOf[ArrayIndexOutOfBoundsException]) by { ex =>
| println(ex)
| -2
| }
aobeh: util.control.Exception.Catch[Int] = Catch()
scala> val h = nfeh or aobeh
h: util.control.Exception.Catch[Int] = Catch()
scala> val task = h apply {
| "120".toInt
| }
task: Int = 120
scala> val task = h apply {
| "12o".toInt
| }
java.lang.NumberFormatException: For input string: "12o"
task: Int = -1
scala> val task = h apply {
| Array(12, 33, 22)(2)
| }
task: Int = 22
scala> val task = h apply {
| Array(12, 33, 22)(6)
| }
java.lang.ArrayIndexOutOfBoundsException: 6
task: Int = -2
我喜欢你的答案,并将根据它简化事情,但请检查dave是否解决了问题的部分功能部分。这真的很有帮助。我写scala已经有一年了,我经常忽略的一件事是使用函数作为参数。谢谢你的提醒!那太圆滑了。前几天我碰到了util.control。我在用NoStackTrace找东西。我总是对每个角落的惊喜感到惊讶…您真的是指在失败案例中打印的第一个logger.debug:“got a Left(vcdgatewayeexception)”而不是“got a Left(NoResponseBodyException)”?