【问题标题】:Want to Log any exception, Instead showing in the UI as Unexpected Exception想要记录任何异常,而不是在 UI 中显示为意外异常
【发布时间】:2012-12-22 07:43:13
【问题描述】:

我正在使用此代码:

Logger.getLogger( SampleAction.class.getName() ).log( Level.SEVERE, null, ex );

用于在 Logger 中记录异常。

除了记录异常,它还在 UI 中显示异常。

如何避免显示此异常?

【问题讨论】:

  • 你说的 UI 是指控制台吗?
  • Romski,它是一个基于摇摆的应用程序,所以它在对话框中的 UI 中显示异常
  • 你能多输入一些吗..
  • 这听起来更像是您的系统/应用程序的功能或Logger
  • 这个异常是不是不能被捕获和处理?

标签: java swing exception logging


【解决方案1】:

如何创建另一个这样的类。

public class Log{
    FileConnection fc;
    OutputStream outStream;
    InputStream inStream;

      Log(String exceptionClass, String errorMessage){
           try{
              fc = (FileConnection)Connector.open("[path]");
              if(!fc.exists())            fc.create();

              inStream = fc.openInputStream();
              outStream = fc.openOutputStream();

               if(inStream!=null)             
                       outStream.write(IOUtilities.streamToBytes(instream)); //use this so overwriting is enabled

               outStream.write((exceptionClass+"\n").getBytes());
               outStream.write((errorMessage+"\n").getBytes()); 
           }
           catch(IOException e){}
           finally{
                  try{
                       inStream.close();
                       outStream.close();
                       fc.close();
                   }catch(Exception e){}
            }
      }

}

然后只需在 try 块的每个捕获处调用 Log 类:

例如

try{
      //your process
}catch(Exception e){
       //call log
       new Log(e.getClassName(), e.getMessage());
}

你可以修改它,最好为每个日志写日期和时间。

【讨论】:

  • 我正在尝试...会尽快通知您。
  • Jj Tuibeo。我尝试了您的建议,但问题是我需要显示整个异常,如堆栈跟踪中所示。但在这种情况下,它只显示堆栈跟踪的第一行。我认为这是因为我们正在使用 e.getMessage()。
  • 我明白了。 getMessage() 不会给你整个堆栈跟踪。我不确定,但我认为有一些方法可以将堆栈跟踪转换为字符串。
  • stackoverflow.com/questions/1149703/… 如果要将堆栈跟踪转换为字符串以将其写入单独的文件中,请尝试此操作。
【解决方案2】:

发生了两件事:

  1. 记录器正在记录异常
  2. 异常未被捕获或被传播,直到另一段代码在对话框中显示它。如果您不希望显示该对话框,则需要在异常显示之前对其进行处理。

请粘贴包含日志记录的整个方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多