Reputation: 478
I am building a map structure by extracting 30-40 keys from unstructured text rows from messy csv data. i am extracting using regex on this messy data row , lot of time those values are not there so it generates exception,
I put these 40-50 statements in try , catch block and able to parse but issue is one exception is generated other statement will not be extracted so I started putting each comment inside a try catch block .
try{
statment: 1
statment:2
.
.
.statement 30
}
how to handle elegantly such scenario in scala to capture exception in each statement and continue building map structure without puting each statement inside separate try catch block.
try{
stat1
}
try{
stat2
}
....
Actual Code:-
var mp = scala.collection.immutable.Map[String, Any]()
try{
// working on json payload
var jsonpayloadstr= cleanstr.split("\"\\{\"")(1).split(",\"\\[")(0).split("\\}\",")(0).toString
jsonpayloadstr ="{\""+jsonpayloadstr +"}"
var jobj=scala.util.parsing.json.JSON.parseFull(jsonpayloadstr)
var bdmap=jobj.get.asInstanceOf[Map[String, Map[String, Any]]]("Boundary")
bdmap.map(x=>mp=mp+(x._1->x._2))
//batterystatus
var batterystatus= jobj.get.asInstanceOf[Map[String, Map[String, Map[String,Double]]]]("Notification")("Data")("BatteryStatus")
mp=mp+("BatteryStatus"->batterystatus.toInt)
var locationMap= jobj.get.asInstanceOf[Map[String, Map[String, Map[String,Map[String,Any]]]]]("Notification")("Data")("Location")
locationMap.map(x=>mp=mp+(x._1->x._2))
//tagid
var tagId= jobj.get.asInstanceOf[Map[String, Map[String, Map[String,Any]]]]("Notification")("Data")("TagID")
mp=mp+("TagID"-> tagId)
//brechID
var isBreached=jobj.get.asInstanceOf[Map[String, Map[String, Map[String,List[Map[String,Any]]]]]]("Notification")("Data")("SensorData")(0)("IsBreached")
mp=mp+("IsBreached"-> isBreached)
}
catch{
case e: Exception => {
println("Oops none get 123455dsdsd677")
}
}
Thanks
Upvotes: 0
Views: 552
Reputation: 478
I came to know a new way from reddit scala forum:-
We shouldn't use exception-based extractions. Put your regexes in a list and map the list with the according extraction function, something like regex => Option[element] and flatten the list after.
Upvotes: 0
Reputation: 6363
If you want to keep on parsing the other variables even if one fails, you can do something like:
val batterystatus = Try(...).toOption
val locationMap = Try(...).toOption
...
That way you'll have values for everything that parsed correctly and you'll be forced to think about how to handle the ones that didn't.
Upvotes: 2