Scala: print a stack trace in my Scalatra app

帅比萌擦擦* 提交于 2019-12-04 17:43:04

问题


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?


回答1:


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.




回答2:


Use ExceptionUtils from Apache Commons Lang:

import org.apache.commons.lang3.exception.ExceptionUtils
(...)
logger.info("an exception occurred: " + ExceptionUtils.getStackTrace(e))



回答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.




回答4:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!