001package arcommon.exception;
002
003import java.lang.Thread.UncaughtExceptionHandler;
004
005import arcommon.DateUtil;
006
007public class MyUncaughtExceptionHandler implements UncaughtExceptionHandler {
008    
009    private static final int TIME_LIMIT_BETWEEN_EXCEPTION = 10; // in seconds
010    private static final int VIEW_IN_DIALOG_LIMIT = 15;
011    private static final int LOG_EXCEPTION_LIMIT = 150;
012    private static final int PRINT_EXCEPTION_LIMIT = 100;
013    private static final int PRINT_SKIPPED_EXCEPTION_LIMIT = 200;
014    
015    private boolean viewInGui;
016
017    private int exceptionCount = 0;
018    private long lastExceptionTime = 0;
019
020    public MyUncaughtExceptionHandler(boolean pviewInGui) {
021        viewInGui = pviewInGui;
022    }
023    
024    public void uncaughtException(Thread t, Throwable e) {
025        try {
026            long currentTimeMilliseconds = System.currentTimeMillis();
027            long diff = currentTimeMilliseconds - lastExceptionTime;
028            if (lastExceptionTime == 0 || diff > TIME_LIMIT_BETWEEN_EXCEPTION * DateUtil.SECOND_IN_MILLISECONDS) {
029                exceptionCount = 0;
030            }
031            lastExceptionTime = currentTimeMilliseconds;
032            
033            ExceptionData exceptionData = new ExceptionData(t, e, currentTimeMilliseconds);
034            
035            exceptionCount++;
036            if (exceptionCount < PRINT_EXCEPTION_LIMIT) {
037                System.err.println(exceptionData.exceptionStackToString(true));
038            } else {
039                if (exceptionCount < PRINT_SKIPPED_EXCEPTION_LIMIT) {
040                    System.err.println("Exception number " + exceptionCount + " skipped");
041                }
042            }
043            
044            if (MyLog.logFileName != null && exceptionCount < LOG_EXCEPTION_LIMIT) {
045                MyLog.logException(exceptionData);
046            }
047
048            if (exceptionCount < VIEW_IN_DIALOG_LIMIT && viewInGui) {
049                ExceptionViewDialog.viewException(exceptionData, null);
050            }
051        } catch (Throwable e1) {
052            System.out.println("Error in error handling!");
053            System.out.println("Error handling exception:");
054            e1.printStackTrace();
055        }
056    }
057}