简体   繁体   English

如何在不使用Try / Catch块的情况下编写此代码?

[英]How do I write this without using a Try/Catch block?

I am looking to rewrite this scala function, but I am new to the language, I understand there is a alternative to using try\\catch blocks. 我希望重写此scala函数,但是我是该语言的新手,我知道可以使用try \\ catch块来替代。 How would you guys rewrite this function? 你们将如何重写此功能?

  def updateStationPost = Action { implicit request =>
    StationForm.bindFromRequest.fold(
      errors => { //needs to be revised!!
        BadRequest(html.updateStation(errors,
             Station(
              request.body.asFormUrlEncoded.get("id")(0).toLong,
              request.body.asFormUrlEncoded.get("operator")(0).toLong,
              request.body.asFormUrlEncoded.get("name")(0),
              try {
                request.body.asFormUrlEncoded.get("number")(0).toInt
              } catch {
                case e:Exception => { 0 } //this exception happens when trying to convert the number when there is nothing in the flash scope to convert.
              },
              request.body.asFormUrlEncoded.get("timezone")(0)
            ),
            Operators.retrieveJustOperators() //ugh... needs to be revised..
          )
        )
      },
      { case(stationFormObj) =>
        Stations.update(stationFormObj)
        Redirect(routes.StationsController.index)
      }
    )
  }

A general way of managing this is to use Try to wrap code that could throw an exception. 管理此问题的一般方法是使用“ 尝试包装”可能引发异常的代码。 Some of the ways of using this are illustrated below: 使用它的一些方法如下所示:

def unpredictable() = {
  Try(Console.readLine("Int please: ").toInt) getOrElse 0
}

If the console read does not contain a parseable integer, then it throws an exception. 如果控制台读取的内容不包含可解析的整数,则它将引发异常。 This code just returns a 0 if there was an error, but you could put other statements there. 如果发生错误,此代码仅返回0,但是您可以在其中放置其他语句。 As an alternative, you could use pattern matching to handle the situation. 或者,您可以使用模式匹配来处理这种情况。

def unpredictable() =  {
  Try(Console.readLine("Int please: ").toInt) match {
    case Success(i) => i
    case Failure(e) => println(e.getMessage()) 
  }
}

You can also just return a Try and let the caller decide how to handle the failure. 您也可以只返回Try,让调用者决定如何处理失败。

How about: 怎么样:

import scala.util.control.Exception.handling

// Create a val like this as you reuse it over and over
val form: Option[Map[String, Seq[String]]] = request.body.asFormUrlEncoded

// Create some helper functions like this
val nfeHandler = handling(classOf[NumberFormatException]) by (_ => 0)
val intNFEHandler = (str: String) => nfeHandler apply str.toInt
val longNFEHandler = (str: String) => nfeHandler apply str.toLong

// You can use this instead of your try catch.. but this is just a sugar.. perhaps cleaner
intNFEHandler apply form.get("id")(0)

Here if the form was something like: Option(Map("id" -> Seq.empty[String])) 这里的形式是这样的: Option(Map("id" -> Seq.empty[String]))

form.get("id")(0) would blow up with java.lang.IndexOutOfBoundsException. form.get("id")(0)会因java.lang.IndexOutOfBoundsException而form.get("id")(0)

I would suggest to have another helper: 我建议再找一个助手:

// takes fieldNames and returns Option(fieldValue)
val fieldValueOpt = (fieldName: String) => form.flatMap(_.get(fieldName).flatMap(_.headOption))

Then create a validate method which performs pattern matching on all the fieldValue optionals, extract the values and create your Station object. 然后创建一个validate方法,该方法对所有fieldValue可选参数执行模式匹配,提取值并创建Station对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 怎么做:在X持续时间内尝试{block of code}并捕获{Exceptions,例如Timeout}? - How to do: Try {block of code} for X duration and catch {Exceptions, such as Timeout}? 我怎样才能在try catch块中初始化val对象? - How could I initialize val object in the try catch block? 如何访问在Spark Scala的catch块中的try catch块之前声明的变量 - How to access variables declared before try catch block in a catch block in spark scala try catch块未捕获异常 - Exception is not caught by the try catch block Kafka Scala:如何将 val 移动到 try catch 块中 - Kafka Scala: How to move val into try catch block 有没有办法确定是否可以调用dialog.dismiss()而不使用空的try-catch块? - Is there a way to determine whether it is possible to call a dialog.dismiss() without empty try-catch block? 什么Scala的“尝试”意味着没有捕获或最终阻止? - What does Scala's “try” mean without either a catch or finally block? 在try / catch块中最终“超出范围” - Is finally “out of scope” in a try/catch block try / catch块的默认构造函数中的问题 - problems in default constructor with try/catch block 如何在不使用RDD的情况下将文本(.txt)文件写入数据框并在控制台上打印 - How do i write a text(.txt) file to a dataframe without using RDDs and print it on a console
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM