Scala error handling – if a part of my Scala code fails, I want to execute a function() as part of the program

huangapple go评论69阅读模式
英文:

Scala error handling - if a part of my Scala code fails, I want to execute a function() as part of the program

问题

我刚开始学习Scala编码,我有一个需求,即在我的Scala代码中的某个部分失败时执行一个函数。
我已经尝试过使用Try/Catch,但是在catch{}块内部,我无法调用func1()函数。任何建议都将很有帮助。谢谢。

object obproc {
  def main(args: Array[String]): Unit = {
    code1

    code2

    code3

    def func1(a: String) {
      //一些功能
    }
    // 如果code2失败,我需要执行函数,如func1("code failed")
  }
}
英文:

I am new to Scala coding, I have a requirement to execute a function if a part of my scala code fails.
I have tried using Try/Catch but inside catch{} block I am not able to call the func1() function. Any suggestions would be helpful. Thanks.

object obproc {
 def main(args: Array[String]): Unit = {
  code1

  code2

  code3

  def func1(a:String) {
 //some functionality
 }
 // if code2 fails I have to execute the function as func1("code failed")
}

}

答案1

得分: 0

如果你只是想在 code1 中捕获任何异常并调用 func1(),可以简单地这样实现:

import scala.util.Try
Try(code1).getOrElse(func1("code 1 failed"))

但这只是一个简单的实现。如果 func1() 失败了会怎么样呢?

正如其他评论中所说,值得考虑在代码库中如何表达和封装失败,以及如何组合它们。

如果我们使用 Try 来封装我们的失败情况,我们可以这样编写:

def code1: Try[Unit] = ???
def func1(a: String): Try[Unit] =  ???
val composedApplication: Try[Unit] = code1.orElse(func1("failed"))

然后在应用程序的顶部运行它:

composedApplication.fold(err => println("failure" + err), _ => println("success"))
英文:

If you simply wanted to catch any exceptions in code1 and call func1(), it could be as simple as:

import scala.util.Try
Try(code1).getOrElse(func1("code 1 failed"))

But this is a crude implementation. What happens if func1() fails?

As others have said in the comments, it is worth thinking about how failures are expressed and encapsulated in the code base. And how they can be composed.

If we were using Try to encapsulate our failures, we could write something like:

def code1: Try[Unit] = ???
def func1(a: String): Try[Unit] =  ???
val composedApplication: Try[Unit] = code1.orElse(func1("failed"))

And then at the very top of the application, run it:

composedApplication.fold(err => println("failure" + err), _ => println("success"))

huangapple
  • 本文由 发表于 2020年9月23日 22:23:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/64030082.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定