我的Spring Boot Service将执行一个任务,并在成功使用0(没有restcontroller)后退出,但我希望它在每个异常时也退出,所以我在一个类上添加了@ControllerAdvice并放入了这个方法:
@ControllerAdvice
@RequiredArgsConstructor
@Slf4j
public class ImportInekData {
final InekService inekService;
final ImportDataService dataService;
public void doTheJob(){
log.info("Fetching new list from Inek.");
UpdatedList updatedList = inekService.getUpdatedList();
List<Standort> toBeUpdated = updatedList.getToBeUpdated();
List<String> toBeDeleted = updatedList.getToBeDeleted();
log.info("List fetched with " + toBeUpdated.size() + " valid entries to be updated and " + toBeDeleted.size() + " entries marked for deletion. ");
log.info("Pushing to DB...");
dataService.importAll(toBeUpdated);
}
@EventListener
public void onStart(ContextStartedEvent start){
log.info("Application started.");
doTheJob();
log.info("Import finished.");
SpringApplication.exit(start.getApplicationContext(), () -> 0);
}
@ExceptionHandler(value = Exception.class)
public String outOnException(Exception e){
log.error("Exception occurred see logs. Stopping..");
SpringApplication.exit(context, () -> -1);
return "dying";
}
}一切正常,但是当我抛出一个IllegalArgumentException时,@ExceptionHandler方法不会被调用。首先,我有一个不带参数的void方法,然后我开始尝试字符串返回和至少一个不需要的参数。
如何让它正常工作?有没有更好的方法让我的案例对每个异常做出反应?
发布于 2021-02-22 05:18:25
spring中的控制器建议是一种旨在正确处理spring MVC级别的异常的机制。
简而言之,Spring MVC是一个web框架,因此,它假设您有某种web端点,可以由最终用户或前端调用。这个端点是后端代码的“入口点”,可以拥有服务、查询数据库等等。如果在此后端流程中抛出异常,通常您不希望web端点返回500内部服务器错误,因此spring提供了工具来方便地映射这些异常:使用“好看”的消息将它们转换为json,使用正确的HTTP代码,等等。
如果你没有任何控制器,那么控制器建议的整个概念在你的流程中是不适用的,所以使用它是没有意义的...
现在真正的问题是,您到底想通过这种异常处理来实现什么?如果应用程序上下文无法启动,通常spring boot应用程序将正常关闭...
如果要以编程方式关闭应用程序,请确保已阅读this thread
https://stackoverflow.com/questions/66276823
复制相似问题