I am using scalatra to "export" a MongoDB data to JSon, my actions are very simple, like:
get("/") {
val title = db.get_collection("main", "api", "title")
send_json(title)
}
I want to send a HTTP error and a text if something go wrong, on the other side it will be converted to something meaninful to the user. So the method becames:
get("/") {
try {
val title = db.get_collection("main", "api", "title")
send_json(title)
} catch {
case e:java.util.NoSuchElementException => send_error("DB malformed", InternalError)
case e:com.mongodb.MongoException => send_error("Can not connect to MongoDB", InternalError)
case e => send_error("Internal Error", InternalError)
}
}
The try catch is bigger that the actual method and I need to do this for every method, the class become at first sight an ugly collection of try catch. There is any way to avoid or minimize the bad looking and distracting try catch all over the code? I am new to Scala (and Java BTW) so I guess I am missing something.
I dont want the DB object to send JSON, so having the try catch on the db.get_collection method is not an option.
There's a special route handler for this:
error {
case e: Throwable => {
redirect("/")
}
}
By changing the case
statement you can switch on the error type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With