java - 在 Java 中提取用户友好的异常详细信息

标签 java logging jakarta-ee exception

我有一个正在处理的 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/

相关文章:

java - 错误: cannot access Filter

java - J2EE 中的应用程序管理事务

java - Seam Solder @MessageBundle 生成实现类 Maven 错误

Java:用于加密的更轻代码

java - 如何禁用速度日志

ssl - 减少 Wildfly 日志中的 javax.net.ssl 噪音

java - GWT 上传示例不起作用?

java - 忽略 ASCII 艺术中的转义序列

java - 无法访问属性

node.js - 在 Node.js 应用程序中实现日志记录