Add exception dialog

This commit is contained in:
mkpaz 2022-09-26 14:09:58 +04:00
parent 78a3299d4b
commit 012dcdd950
3 changed files with 67 additions and 10 deletions

@ -0,0 +1,65 @@
/* SPDX-License-Identifier: MIT */
package atlantafx.sampler;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Objects;
import static java.lang.Double.MAX_VALUE;
public class DefaultExceptionHandler implements Thread.UncaughtExceptionHandler {
private final Stage stage;
public DefaultExceptionHandler(Stage stage) {
this.stage = stage;
}
@Override
public void uncaughtException(Thread t, Throwable e) {
e.printStackTrace();
var dialog = createExceptionDialog(e);
if (dialog != null) { dialog.showAndWait(); }
}
private Alert createExceptionDialog(Throwable throwable) {
Objects.requireNonNull(throwable);
var alert = new Alert(AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText(null);
alert.setContentText(throwable.getMessage());
try (var sw = new StringWriter(); var printWriter = new PrintWriter(sw)) {
throwable.printStackTrace(printWriter);
var label = new Label("Full stacktrace:");
var textArea = new TextArea(sw.toString());
textArea.setEditable(false);
textArea.setWrapText(false);
textArea.setMaxWidth(MAX_VALUE);
textArea.setMaxHeight(MAX_VALUE);
var content = new VBox(5, label, textArea);
content.setMaxWidth(MAX_VALUE);
alert.getDialogPane().setExpandableContent(content);
alert.initOwner(stage);
return alert;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}

@ -40,21 +40,13 @@ public class Launcher extends Application {
new KeyCodeCombination(KeyCode.F, KeyCombination.CONTROL_DOWN)
);
private static class DefaultExceptionHandler implements Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) {
Thread.currentThread().setUncaughtExceptionHandler(new DefaultExceptionHandler());
Thread.currentThread().setUncaughtExceptionHandler(new DefaultExceptionHandler(stage));
loadApplicationProperties();
if (IS_DEV_MODE) {

@ -117,7 +117,7 @@ public class DialogPage extends AbstractPage {
var button = new Button("Click", new FontIcon(Feather.MEH));
button.setOnAction(e -> {
var alert = new Alert(AlertType.ERROR);
alert.setTitle("Error Dialog");
alert.setTitle("Exception Dialog");
alert.setHeaderText(randomHeader());
alert.setContentText(FAKER.lorem().paragraph(3));