我希望重写这个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)
}
)
}
答案 0 :(得分:1)
管理此方法的一般方法是使用Try来包装可能引发异常的代码。使用它的一些方法如下所示:
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并让调用者决定如何处理失败。
答案 1 :(得分:0)
怎么样:
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。
我建议有另一个帮手:
// takes fieldNames and returns Option(fieldValue)
val fieldValueOpt = (fieldName: String) => form.flatMap(_.get(fieldName).flatMap(_.headOption))
然后创建一个validate方法,在所有fieldValue选项上执行模式匹配,提取值并创建Station对象。