Search code examples
c#exceptionquartz.net

Handle JobExecutionException in Quartz.net


Probably a stupid question... but here goes anyway...

I have set up quartz, and can schedule jobs, and I can confirm that jobs (implementing the IJob interface) are working.

Looking at the documentation on the site, (Lesson 3 of the tutorial):

The only type of exception that you are allowed to throw from the execute method is JobExecutionException.

I would like that when an exception occurs that I haven't explicitly handled, it should throw a JobExecutionException, so that I can log it in the 'parent' application. I have wrapped my code in a try catch, and have thrown the JobExecutionException, but now where to handle it?

I don't call the execute method anywhere, that is handled by Quartz (on a separate thread). So, how do I handle that error when it occurs. I don't really want to swallow the error in the Job


Solution

  • Typically you would set up the execute method of your job as follows:

    try
    {
        // the work you want to do goes here
    }
    catch (ExceptionTypeYouWantToHandle1 ex1)
    {
        // handle exception
    }
    catch (ExceptionTypeYouWantToHandle2 ex2)
    {
        // handle exception
    }
    // and so on
    catch (Exception ex)
    {
        // something really unexpected happened, so give up
        throw new JobExecutionException("Something awful happened", ex, false); // or set to true if you want to refire
    }
    

    At this point the scheduler itself will log the exception to wherever it is logging (based on the configuration).