How to get the exception details of a failed background job with Hangfire

Viewed 846

I'm using Hangfire to fire off some background jobs, then I am checking their progress looking for failed jobs using:

IStorageConnection connection = JobStorage.Current.GetConnection();
JobData jobData = connection.GetJobData(jobId);

if (jobData.State == FailedState.StateName)
   // Some how get exception details

I would like to get the Exception thrown that caused the job to fail. (I am throwing new Exception("test error") in my job currently to test it out).

I can't seem to find any docs or examples on how I can get this information, is it possible?

1 Answers

After seeing an answer on another question which used the GetMonitoringApi, I was able to use it here to get the exception message like so:

if (jobData.State == FailedState.StateName)
{
  var failedJobsCount = JobStorage.Current.GetMonitoringApi()
      .FailedCount();

  var failedJob = JobStorage.Current.GetMonitoringApi()
      .FailedJobs(0, (int)failedJobsCount)
      .Where(j => j.Key == jobId)
      .SingleOrDefault();
  
  var exceptionMsg = failedJob.Value.ExceptionMessage;
}

This gives me the "test error" message that was thrown from my job. Success!

Related