title: Hangfire job is crashing the entire application; how do we get Hangfire to handle the errors?
body: <p>We have several Hangfire jobs, and occasionally they will bring down our entire site. Hangfire isn't catching the errors, and we even added a try/catch around the ProcessCore() call, but it's not hitting that code.</p>
  <p>Has anyone else had this issue? Is there some kind of specific setup that needs to be done to avoid this? (In the error below, BackgroundServices.UpdateClientStats is the Hangfire job)</p>
  <pre><code>RecurringJob.AddOrUpdate(&quot;updateClientStats&quot;, () =&gt; container.GetInstance&lt;UpdateClientStats&gt;().Process(null), Cron.Daily(7));
  
  
  
  
  public class UpdateClientStats : BackgroundAppService {
          private readonly ClientStatsHelper clientStatsHelper;
          public UpdateClientStats(DBContext context, IDomainRuleViolationCollection domainRuleViolationCollection, ClientStatsHelper clientStatsHelper) : base(context, domainRuleViolationCollection) {
              this.clientStatsHelper = clientStatsHelper;
          }
  
         protected async override Task ProcessCore() {
              var userIds = context.Users.Where(x =&gt; x.Status == ClientStatus.Active &amp;&amp; x.TeamMemberRole.HasFlag(TeamMemberRole.Runner)).Select(x =&gt; x.Id).ToList();
  
              userIds.ForEach(async userId =&gt; {
                  await clientStatsHelper.UpdateClientStats(userId, false, false);
              });
          }
      }
  
  
  public async Task UpdateClientStats(long clientUserId, bool skipJournalEntries, bool skipLastScheduledWorkoutDate) {
              using (var scope = serviceScopeFactory.CreateScope()) {
                  var context = scope.ServiceProvider.GetService&lt;DBContext&gt;();
  
  ... more code logic here...
  
                  var user = await context.Users.Where(x =&gt; x.Id == clientUserId).FirstOrDefaultAsync();
  
                  if (user != null) {
                      user.UpdateNextScheduledEvent(await Helpers.ClientHelper.GetClientNextEventDate(context.ClientProgramWorkoutDays.AsQueryable(), clientUserId));
  
  ... more logic here...
  
                      user.UpdateStats(completionPercentage, pastCompletionPercentage, durations7Days.Miles, durationsPast7Days.Miles, durations7Days.TimeInSeconds,
                          durationsPast7Days.TimeInSeconds, durations30Days.Miles, durationsPast30Days.Miles, durations30Days.TimeInSeconds, durationsPast30Days.TimeInSeconds,
                          durationsTrailing7to34Days.Miles, durationsTrailing7to34Days.TimeInSeconds, intensityInSeconds7Days, intensityInSecondsTrailing7to34Days);
  
  
                      await context.SaveChangesAsync();
                  }
              }
          }
  
  
  
  public abstract class BackgroundAppService : BaseAppService {
          public BackgroundAppService(DBContext context, IDomainRuleViolationCollection domainRuleViolationCollection) : base(context, domainRuleViolationCollection) {
  
          }
          protected abstract Task ProcessCore();
  
          [DisableConcurrentExecution(timeoutInSeconds: 10)]
          [AutomaticRetry(Attempts = 0, OnAttemptsExceeded = AttemptsExceededAction.Delete)]
          public void Process(PerformContext performContext) {
              using (LogContext.PushProperty(&quot;ApplicationName&quot;, &quot;Hangfire&quot;))
              using (LogContext.PushProperty(&quot;Hangfirejob&quot;, this.GetType().Name))
              using (LogContext.PushProperty(&quot;HangfireJobID&quot;, performContext?.BackgroundJob?.Id))
              using (LogContext.Push(new PerformContextEnricher(performContext))) {
                  Log.Information(&quot;Job {jobName} Started&quot;, this.GetType().Name);
  
                  try {
                      ProcessCore().Wait();
                  } catch (Exception ex) {
                      Log.Error(ex.ToString());
                      throw ex;
                  }
  
                  Log.Information(&quot;Job {jobName} Finished&quot;, this.GetType().Name);
              }
  
          }
  
      }```
  
  
  Your app crashed because of System.InvalidOperationException
  
  Your app, crashed because of System.InvalidOperationException and aborted the requests it was processing when the overflow occurred. As a result, your app’s users may have experienced HTTP 502 errors.
  
  This call stack caused the exception:
  
  Microsoft.Data.Common.ADP.ExceptionWithStackTrace
  System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification
  Microsoft.EntityFrameworkCore.Storage.RelationalConnection+d__50.MoveNext
  System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw
  Microsoft.EntityFrameworkCore.Storage.RelationalConnection+d__50.MoveNext
  System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification
  Microsoft.EntityFrameworkCore.Storage.RelationalConnection+d__47.MoveNext
  System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification
  Microsoft.EntityFrameworkCore.Storage.RelationalCommand+d__17.MoveNext
  System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification
  Microsoft.EntityFrameworkCore.Query.RelationalShapedQueryCompilingExpressionVisitor+AsyncQueryingEnumerable`1+AsyncEnumerator+d__17[[System.__Canon System.Private.CoreLib]].MoveNext
  System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification
  Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor+d__20`1[[System.__Canon System.Private.CoreLib]].MoveNext
  System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw
  Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor+d__20`1[[System.__Canon System.Private.CoreLib]].MoveNext
  System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification
  OurApp.Application.Helpers.ClientStatsHelper+d__2.MoveNext
  System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification
  OurApp.Application.BackgroundServices.UpdateClientStats+&lt;b__2_2&gt;d.MoveNext
  System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw
  System.Threading.Tasks.Task+&lt;&gt;c.b__139_1
  System.Threading.QueueUserWorkItemCallback+&lt;&gt;c.&lt;.cctor&gt;b__6_0
  System.Threading.ExecutionContext.RunForThreadPoolUnsafe[[System.__Canon System.Private.CoreLib]]
  System.Threading.QueueUserWorkItemCallback.Execute
  System.Threading.ThreadPoolWorkQueue.Dispatch
  System.Threading._ThreadPoolWaitCallback.PerformWaitCallback
  </code></pre>