Scala 如何在不使用Try/Catch块的情况下编写此代码?
我希望重写这个scala函数,但我对该语言还不熟悉,我知道除了使用try\catch块,还有其他选择。你们怎么重写这个函数Scala 如何在不使用Try/Catch块的情况下编写此代码?,scala,try-catch,playframework-2.2,Scala,Try Catch,Playframework 2.2,我希望重写这个scala函数,但我对该语言还不熟悉,我知道除了使用try\catch块,还有其他选择。你们怎么重写这个函数 def updateStationPost = Action { implicit request => StationForm.bindFromRequest.fold( errors => { //needs to be revised!! BadRequest(html.updateStation(errors,
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)
}
)
}
那么:
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))
然后创建一个验证方法,该方法对所有fieldValue选项执行模式匹配,提取值并创建站点对象。管理该方法的一般方法是使用包装可能引发异常的代码。使用此功能的一些方法如下所示:
def unexpective()={
Try(Console.readLine(“Int-please:”).toInt)getOrElse 0
}
如果控制台读取不包含可解析的整数,则会引发异常。如果有错误,这段代码只返回0,但您可以将其他语句放在那里。作为替代方案,您可以使用模式匹配来处理这种情况
def unexpective()={
尝试(Console.readLine(“Int-please:”).toInt)匹配{
案例成功率(i)=>i
案例失败(e)=>println(e.getMessage())
}
}
您也可以返回一个Try,让调用方决定如何处理故障。很高兴它很有用!签出选项并将其作为有用的附件进行尝试。