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?
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.
Use ExceptionUtils from Apache Commons Lang:
import org.apache.commons.lang3.exception.ExceptionUtils
(...)
logger.info("an exception occurred: " + ExceptionUtils.getStackTrace(e))
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.
This question has several ways to convert an exception stack trace to a String. printStackTrace outputs to System.err unless you provide a writer.
来源:https://stackoverflow.com/questions/18880126/scala-print-a-stack-trace-in-my-scalatra-app