【发布时间】:2018-01-31 16:47:01
【问题描述】:
我在 IntelliJ 中有一个 Spring Boot 应用程序,最初配置为正常启动,如下所示:
public static void main(String[] args) throws Exception {
SpringApplication.run(AccountApiApplication.class, args).close();
}
我在main 方法中添加了一个try-catch 块来处理启动过程中发生的任何错误(例如缺少配置文件等),现在它看起来像:
public static void main(String[] args) throws Exception {
try {
SpringApplication.run(AccountApiApplication.class, args).close();
}
catch(Exception e) {
e.printStackTrace();
System.exit(1);
}
}
添加后,我的应用程序总是以退出代码 1 退出。即使没有错误。我尝试打印正在发生的异常,它是这样的:
org.springframework.boot.devtools.restart.SilentExitExceptionHandler$SilentExitException
at org.springframework.boot.devtools.restart.SilentExitExceptionHandler.exitCurrentThread(SilentExitExceptionHandler.java:90)
at org.springframework.boot.devtools.restart.Restarter.immediateRestart(Restarter.java:184)
at org.springframework.boot.devtools.restart.Restarter.initialize(Restarter.java:163)
at org.springframework.boot.devtools.restart.Restarter.initialize(Restarter.java:552)
at org.springframework.boot.devtools.restart.RestartApplicationListener.onApplicationStartingEvent(RestartApplicationListener.java:67)
at org.springframework.boot.devtools.restart.RestartApplicationListener.onApplicationEvent(RestartApplicationListener.java:45)
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:167)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:122)
at org.springframework.boot.context.event.EventPublishingRunListener.starting(EventPublishingRunListener.java:68)
at org.springframework.boot.SpringApplicationRunListeners.starting(SpringApplicationRunListeners.java:48)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151)
at edu.iu.es.ebs.AccountApiApplication.main(AccountApiApplication.java:90)
Process finished with exit code 1
为什么即使应用程序中没有错误,我也会看到此异常?当我们这样做时,有没有比在 main 中添加 try-catch 更好的方法来处理不可预测的启动错误?
【问题讨论】:
-
你为什么要用这个
.close()关闭你的应用程序? -
@pvpkiran 因为如果我不这样做,它就不会退出。我的意思是它不会以“进程以退出代码 0 结束”或“进程以退出代码 1 结束”之类的方式结束。它以“Started Application ...”结束。我最终将通过 shell 脚本调用应用程序,因此我需要它结束并向脚本返回退出代码。
-
@lebowski 这是一个不同的问题。如果您检查 Spring Boot 应用程序生命周期 (docs.spring.io/spring-boot/docs/current/reference/html/…),您可以看到应用程序在准备好工作时处于“已启动应用程序”上是正常的。如果您需要“最终”执行,您应该检查
Schedule功能
标签: java spring spring-boot exception-handling exit-code