Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global exception handler for java spring console application

Im working on small console application. In some places in my code i'm throwing custom RuntimeExceptions when something bad happens. What i'm looking for is a global exception handler that i can use to catch my exceptions and display proper information for user (also log them).

So my idea is to use try-catch in here:

@SpringBootApplication
public class TfsWorkReporterApplication {

    public static void main(String[] args) {
        try {
            SpringApplication.run(TfsWorkReporterApplication.class, args);
        } catch(CustomException ex){
            //Display user information.
        }
    }
}

But my sixth sense tells me that this isn't the proper way to do it. Any help?


1 Answers

You can try using @ControllerAdvice but I am not sure if it will work for standalone application, for web application works, something like this

@ControllerAdvice
public class GlobalDefaultExceptionHandler {
   @ExceptionHandler(value = CustomException.class)
   public void defaultErrorHandler(CustomException e) {
       //handle here
   }
}
like image 62
user2669657 Avatar answered Feb 06 '26 11:02

user2669657