0

I use this code to run Spring tasks:

@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);
    }

But sometimes I get SQL error. What is the best way to intercept errors? Should I use classical try-catch block or there is a listener for the task?

Peter Penzov
  • 1,126
  • 134
  • 430
  • 808
  • Yes, you should use try-catch block to get the exception and that will provide more information regarding the SQL error. That's typical coding style. – Pranay Apr 17 '19 at 09:47
  • `try{}catch(SQLException exception){}` by using try-catch you have more control on it as a developer. Or look at [Exception handling for Spring 3.2 “@Scheduled” annotation](https://stackoverflow.com/questions/24031613/exception-handling-for-spring-3-2-scheduled-annotation) – Sudhir Ojha Apr 17 '19 at 09:49
  • configuring your TaskScheduler set the ErrorHandler on it – IMParasharG Apr 17 '19 at 09:56
  • but when I get exception I would like to log it using SQL query. How I can do this using annotation? Can I send it as Object? – Peter Penzov Apr 17 '19 at 09:57
  • When defining methods that throw exceptions it is best to be avoid throwing `Exception` and try to throw something more specific like `SQLException` this will improve the calling code as it won't have to catch and deal with every subclass of `Exception` – Gavin Apr 17 '19 at 09:58

1 Answers1

1

I'd suggest using try catch with SQLException is best bet as you're running @Schedule - possibly you don't want to break it,

@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
 }
}
Milan Desai
  • 1,228
  • 8
  • 23