Search code examples
javaspringspring-bootmessagebox

Reporting Errors In Spring Boot Startup


When my application.yml does not match the database schema properly in my springboot application it will fail to start with a very verbose exception trace.

This trace is very difficult for a user to parse, even if I log the failure reason, it will be lost in a barrage of logs.

Worse yet, if the user launcher the program from a shortcut it will disappear and they will need to dig up the log or run it from the command line.

I would like to popup a message box right when I encounter the problem.

I tried adding a JOptionPane.showMessageDialog but this throws a java.awt.HeadlessException.

Is there a more canonical way to provide user feedback when a spring boot application fails to start?


Solution

  • Spring Boot app is headless by default - it means there is no GUI supposed. JOptionPane.showMessageDialog - is part of GUI Java Swing framework.

    So to use this GUI feature, you need to make you Spring Boot not headless.

    Example (short version of code from here):

    @SpringBootApplication
    public class DemoSbSwingApplication extends JFrame {
        public static void main(String[] args) {
            var ctx = new SpringApplicationBuilder(DemoSbSwingApplication.class)
                    .headless(false)
                    .run(args);
            EventQueue.invokeLater(() -> {
                var ex = ctx.getBean(DemoSbSwingApplication.class);
                ex.setVisible(true);
            });
        }
    
        public DemoSbSwingApplication() {
            var pane = getContentPane();
    
            JOptionPane.showMessageDialog(pane, "TEST TEST TEST");
        }
    
    }