Skip to content

Commit

Permalink
Resoday: set default UncaughtExceptionHandler
Browse files Browse the repository at this point in the history
A bunch of places in Resoday's code can generate unchecked exceptions.
Set a default UncaughtExceptionHandler when starting the program.

https://stackoverflow.com/a/588656/1083697
  • Loading branch information
rybak committed Jul 9, 2022
1 parent c321553 commit 6ec6771
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
- Custom data directory setting has been introduced
- Simple crash handler has been introduced

v1.2
- Java 17 is now required to run Resoday
Expand Down
33 changes: 33 additions & 0 deletions src/main/java/dev/andrybak/resoday/Resoday.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,14 @@
import dev.andrybak.resoday.settings.storage.CustomDataDirectory;
import dev.dirs.ProjectDirectories;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import java.awt.BorderLayout;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
Expand All @@ -13,6 +20,10 @@
public final class Resoday {

public static void main(String... args) {
Thread.setDefaultUncaughtExceptionHandler((thread, throwable) -> {
showCrashError(thread, throwable);
System.exit(1);
});
Path dataDir;
Path configDir;
if (args.length < 1) {
Expand Down Expand Up @@ -58,4 +69,26 @@ private static Path getDataDir(Path configDir, Path defaultDataDir) {
}
return dataDir;
}

private static void showCrashError(Thread thread, Throwable t) {
JPanel message = new JPanel(new BorderLayout());
message.add(new JLabel("Uncaught exception: " + t.getMessage()), BorderLayout.NORTH);
{
JTextArea exceptionText = new JTextArea();
StringWriter sw = new StringWriter();
PrintWriter printWriter = new PrintWriter(sw);
printWriter.println("Uncaught exception in thread " + thread.getName());
printWriter.println(t.getMessage());
t.printStackTrace(printWriter);
exceptionText.setText(sw.toString());
message.add(exceptionText, BorderLayout.CENTER);
}
message.add(new JLabel(StringConstants.APP_NAME_GUI + " is going to close"), BorderLayout.SOUTH);
JOptionPane.showMessageDialog(
JOptionPane.getRootFrame(),
message,
"Crash",
JOptionPane.ERROR_MESSAGE
);
}
}

0 comments on commit 6ec6771

Please sign in to comment.