scalaexceptionscalatra

Scala: print a stack trace in my Scalatra app


Seems like a fairly straight forward problem, but I'd like to log a stack trace when my top level error handler in Scalatra is triggered. I'm intentionally throwing an exception in one of my methods by doing something as trivial as:

throw new IllegalArgumentException

In the error handler, the code looks like the following:

 error {
  case e => {
    val logger = LoggerFactory.getLogger(getClass)
    logger.info("an exception occurred: " + e.getStackTrace())
    logger.info("the request body is: " + request)
    NotFound("An error occurred, please contact support")
  }
}

The error handler itself is Scalatra specific, but I'm pretty sure the answer I'm looking for can be solved using any vanilla Scala technique. Is there something I can do at this point to grab the stacktrace? I'm not sure if the request is on the same thread as the error handler, otherwise there might be some answer there. e.getStackTrace() gives me [Ljava.lang.StackTraceElement;@1f6b6954

What's the best way to get a stack trace here printed out so I can log and review it to fix errors in my terrible code?


Solution

  • I think you want printStackTrace() rather than getStackTrace. If you are outputting to a log file, getMessage() may be helpful. Or you may try passing the whole exception object to the logger.