View Javadoc
1   package com.nilhcem.fakesmtp.core.exception;
2   
3   import org.slf4j.Logger;
4   import org.slf4j.LoggerFactory;
5   
6   import javax.swing.JOptionPane;
7   import javax.swing.SwingUtilities;
8   import java.awt.Component;
9   
10  /**
11   * Intercepts every uncaught exception.
12   *
13   * @author Nilhcem
14   * @since 1.1
15   * @see <a href="link">http://stuffthathappens.com/blog/2007/10/07/programmers-notebook-uncaught-exception-handlers/</a>;
16   */
17  public final class UncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
18  
19  	private Component parentComponent;
20  	private static final Logger LOGGER = LoggerFactory.getLogger(UncaughtExceptionHandler.class);
21  
22  	/**
23  	 * Called when an uncaught exception is thrown. Will display the error message in a dialog box.
24  	 *
25  	 * @param t the thread where the exception was throws.
26  	 * @param e the thrown exception.
27  	 */
28  	@Override
29  	public void uncaughtException(final Thread t, final Throwable e) {
30  		try {
31  			if (SwingUtilities.isEventDispatchThread()) {
32  				showException(t, e);
33  			} else {
34  				SwingUtilities.invokeLater(new Runnable() {
35  					public void run() {
36  						showException(t, e);
37  					}
38  				});
39  			}
40  		} catch (Exception excpt) {
41  			LOGGER.error("", excpt);
42  		}
43  	}
44  
45  	/**
46  	 * Sets the parent component where an error dialog might be displayed.
47  	 *
48  	 * @param parentComponent a component where an error dialog might be displayed.
49  	 */
50  	public void setParentComponent(Component parentComponent) {
51  		this.parentComponent = parentComponent;
52  	}
53  
54  	/**
55  	 * Displays an error dialog describing the uncaught exception.
56  	 *
57  	 * @param t the thread where the exception was throws.
58  	 * @param e the thrown exception.
59  	 */
60  	private void showException(Thread t, Throwable e) {
61  		LOGGER.error("", e);
62  		String msg = String.format("Unexpected problem on thread %s: %s", t.getName(), e.getMessage());
63  		JOptionPane.showMessageDialog(parentComponent, msg);
64  	}
65  }