Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to catch all the errors in any scalatra action?

Tags:

scala

scalatra

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.

like image 426
user1216071 Avatar asked Feb 28 '12 11:02

user1216071


1 Answers

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.

like image 90
knub Avatar answered Sep 18 '22 21:09

knub