将异常捕获到Spring Job中

时间:2019-04-17 09:43:25

标签: java spring spring-boot

我使用以下代码运行Spring任务:

@Scheduled(fixedRate = 90000)
    public void myScheduler() throws Exception {

        ZonedDateTime zonedDateTime = ZonedDateTime.now(zone);

        DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM d yyyy  hh:mm a");
        String time = zonedDateTime.format(format);

        System.out.printf("Scheduler exectuted (%s, (%s))\n", time, zone);

        TaskLogs task = new TaskLogs();
        task.setStatus("completed");
        task.setCreatedAt(LocalDateTime.now());
        task.setLog("Executing Notification Job");
        task.setTask_name("Executing Notification Job at " + time + " (" + zone + ")");

        taskLogsService.save(task);
    }

但有时会出现SQL错误。拦截错误的最佳方法是什么?我应该使用经典的try-catch块还是该任务有一个侦听器?

1 个答案:

答案 0 :(得分:1)

我建议将try catch与SQLException一起使用是最好的选择,因为您正在运行@Schedule-可能不想破坏它,

@Scheduled(fixedRate = 90000)
public void myScheduler() throws SQLException {

 ZonedDateTime zonedDateTime = ZonedDateTime.now(zone);

 DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM d yyyy  hh:mm a");
 String time = zonedDateTime.format(format);

 System.out.printf("Scheduler exectuted (%s, (%s))\n", time, zone);

 TaskLogs task = new TaskLogs();
 task.setStatus("completed");
 task.setCreatedAt(LocalDateTime.now());
 task.setLog("Executing Notification Job");
 task.setTask_name("Executing Notification Job at " + time + " (" + zone + ")");
 try {
  taskLogsService.save(task);
 } catch (SQLException sqle){
 System.out.println(sqle);
 //or you can use slf4j logger to record same in logfile
 }
}