Swing Thread Exception Capture

How to send exception to log4j log from java swing?

We already have a lot of code, and it does a lot:

mytable.getSelectionModel().addListSelectionListener(
        new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                ... no try catch
            }
        });

No attempt / catch. The application sends an npe exception to the console. We need this in log4j. But I do not want to change all this code (100 lines of a line, like this). What we can do?

+5
source share
2 answers

You can configure an uncaught-exception handler that will log everything that was created by your application.

In the main method of your Swing application, add the following lines:

Thread.setDefaultUncaughtExceptionHandler(new LoggingExceptionHandler());
System.setProperty("sun.awt.exception.handler", LoggingExceptionHandler.class.getName());

Then we implement the exception handler as follows:

package com.initech.tps;

import java.lang.Thread.UncaughtExceptionHandler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LoggingExceptionHandler implements UncaughtExceptionHandler
{

  private static final Logger logger = LoggerFactory.getLogger(LoggingExceptionHandler.class);

  @Override
  public void uncaughtException(Thread t, Throwable e)
  {
      logger.error("caught exception in thread: " + t.getName(), e);
  }
}
+7
source

EventQueue, : javax.swing

, , , , .

import java.awt.AWTEvent;
import java.awt.EventQueue;

import javax.swing.JOptionPane;

import org.slf4j.Logger;


public class QueueEvenement extends EventQueue {
    // CONSTRUCTOR
    public QueueEvenement(Logger logger) {
        super();
        this.logger = logger;
    }


    protected void dispatchEvent(AWTEvent newEvent) {
        try {
            super.dispatchEvent(newEvent);
        } catch (Throwable t) {
            // Write log
            logger.error(String.format("Erreur inconnue (%s - %s)",
                    t.getClass().getName(), t.getLocalizedMessage()));
        }
    }
}

:

Toolkit.getDefaultToolkit().getSystemEventQueue().push(new EventQueueProxy());

, , , , ( ) .

!

+1

All Articles