如何将函数提升异常转换为函数返回? [英] How to convert functions raising exceptions to functions returning Either?

查看:161
本文介绍了如何将函数提升异常转换为函数返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有几个引发异常的函数。我正在包装它们返回 [Throwable,< function return type>] 。 (让我们假设我需要 而不是尝试)。

  def fooWrapper(arg1:FooArg1,arg2:FooArg2)= 
try Right(foo(arg1,arg2))catch {case NonFatal(e)=> left(e)}

def barWrapper(arg1:BarArg1,arg2:BarArg2,a3:BarArg3)=
try Right(bar(arg1,arg2,artg3))catch {case NonFatal e)=>左(e)}

...

现在我想编写一个通用的包装器来摆脱扩展代码。你会建议什么?

解决方案

我会写这样的形式:

  def wrap [Value](f:=> Value):[Value,Exception] = try {
右(f).right
}
catch {
case ex:Exception => left(ex).right
}

def foo(arg1:FooArg1,arg2:FooArg2)= wrap {
//以前在foo
}

但这不构成。 尝试更好。



更新:如果您只想处理正确的投影,然后只是返回正确的投影。现在它组成了。


Suppose I have a few functions that raise exceptions. I am wrapping them to return Either[Throwable, <function return type>]. (Let's assume I need Either rather than Try).

def fooWrapper(arg1: FooArg1, arg2: FooArg2) =
  try Right(foo(arg1, arg2)) catch { case NonFatal(e) => Left(e) }

def barWrapper(arg1: BarArg1, arg2: BarArg2, a3: BarArg3) =
  try Right(bar(arg1, arg2, artg3)) catch { case NonFatal(e) => Left(e) }

...

Now I would like to write a generic wrapper to get rid of the bolierpllate code. What would you suggest ?

解决方案

I would write something of the form like this:

 def wrap[Value](f: => Value): Either[Value, Exception] = try{
   Right(f).right
 }
 catch{
   case ex: Exception => Left(ex).right
 }

 def foo(arg1: FooArg1, arg2: FooArg2) = wrap{
   //anything I'd have written before in foo
 }

but this doesn't compose. Try is so much nicer.

Updated: If you only ever want to deal with the right projection, then just return the right projection. Now it composes.

这篇关于如何将函数提升异常转换为函数返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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