【发布时间】:2021-05-22 09:36:45
【问题描述】:
我的 Spring Boot 服务将完成一项工作并在成功后以 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 方法,然后我开始尝试使用 String 返回和至少一个参数 - 这不是必需的。
如何使它工作?有没有更好的方法让我的案例对每个异常做出反应?
【问题讨论】:
-
全班分享。
-
@ControllerAdvice仅适用于控制器。你真的从你的控制器中抛出异常吗?你说你有工作,所以可能不正确? -
已更新,添加完整类在使用中