簡體   English   中英

如何在不使用Try / Catch塊的情況下編寫此代碼?

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

我希望重寫此scala函數,但是我是該語言的新手,我知道可以使用try \\ catch塊來替代。 你們將如何重寫此功能?

  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)
      }
    )
  }

管理此問題的一般方法是使用“ 嘗試包裝”可能引發異常的代碼。 使用它的一些方法如下所示:

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

如果控制台讀取的內容不包含可解析的整數,則它將引發異常。 如果發生錯誤,此代碼僅返回0,但是您可以在其中放置其他語句。 或者,您可以使用模式匹配來處理這種情況。

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

您也可以只返回Try,讓調用者決定如何處理失敗。

怎么樣:

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)

這里的形式是這樣的: Option(Map("id" -> Seq.empty[String]))

form.get("id")(0)會因java.lang.IndexOutOfBoundsException而form.get("id")(0)

我建議再找一個助手:

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

然后創建一個validate方法,該方法對所有fieldValue可選參數執行模式匹配,提取值並創建Station對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM