我有一个正在处理的 J2EE Web 应用程序,当发生异常时,我想获取有关异常的一些基本详细信息并将其记录下来。我正在记录的消息应该是非常基本的,可能对运行 Web 服务器的人有意义。
使用 e.getMessage()
是最好的记录方式吗?谢谢。
最佳答案
可能吧。问题是,至少没有调用方法信息,这不是很有帮助
考虑如下内容
/**
* Returns <i>class.method:linenumber</i> of the caller (or, more accurately
* the caller of the caller).
* </p>
*
* <p>
* Returns unknown if stacktrace is mucked up. Uses reflection and string
* concatenation, so don't overuse this for trivial matters. For exception
* handling and for logging, on the other hand, it is useful.
*
* @return method name of caller's caller and line number (String)
*/
public static String returnCaller( Class ignoreMe )
{
String ignoreClass = ignoreMe.getName();
StackTraceElement[] steArr = new Throwable().getStackTrace();
if (steArr != null)
{
// subscript 1 is returnCaller().
// subscript 2 is the caller of returnCaller()
// subscript 3 is the caller of the caller of returnCaller()...
for( int i = 0; i < steArr.length; i++)
{
if (steArr[i] == null)
break;
String myclass = steArr[i].getClassName();
if (myclass.equals(ErrorHandle.class.getName()))
continue;
if (ignoreClass.equals(myclass))
continue;
return steArr[i].getClassName()
+ "."
+ steArr[i].getMethodName()
+ ":"
+ steArr[i].getLineNumber();
}
}
return "unknown";
}
关于java - 在 Java 中提取用户友好的异常详细信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2790528/