Scala: print a stack trace in my Scalatra app
Asked Answered
E

4

14

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?

Elissa answered 18/9, 2013 at 18:55 Comment(0)
M
6

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.

Minta answered 18/9, 2013 at 19:6 Comment(0)
S
7

Use ExceptionUtils from Apache Commons Lang:

import org.apache.commons.lang3.exception.ExceptionUtils
(...)
logger.info("an exception occurred: " + ExceptionUtils.getStackTrace(e))
Stonewort answered 27/6, 2014 at 20:20 Comment(0)
M
6

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.

Minta answered 18/9, 2013 at 19:6 Comment(0)
F
3

If you use the standard logger: com.typesafe.scalalogging.Logger , the logger prints the stack trace for you.

You can just use it this way:

import com.typesafe.scalalogging.Logger
import org.slf4j.LoggerFactory

try {     
    throw new Exception("test message")
} catch {
    case e:Exception => logger.error("Exception " , e)
}

There is already an overload which is accepting 2 parameters, String and Throwable.

Frizzy answered 2/11, 2017 at 18:18 Comment(0)
M
2

This question has several ways to convert an exception stack trace to a String. printStackTrace outputs to System.err unless you provide a writer.

Mcchesney answered 18/9, 2013 at 19:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.