So I can pump exceptions caught in a background job to something like https://github.com/NickCraver/StackExchange.Exceptional ?
I'm not sure about the hook thing, but you can manage exceptions in jobs using a JobFilter, and then reporting the exception to the external service.
public class ErrorReportingJobFilter : JobFilterAttribute, IElectStateFilter
{
public void OnStateElection(ElectStateContext context)
{
// the way Hangfire works is retrying a job X times (10 by default), so this wont be called directly with a
// failed state sometimes.
// To solve this we should look into TraversedStates for a failed state
var failed = context.CandidateState as FailedState ??
context.TraversedStates.FirstOrDefault(x => x is FailedState) as FailedState;
if (failed == null)
return;
//here you have the failed.Exception and you can do anything with it
//and also the job name context.Job.Type.Name
}
}
and then register the Job filter globally
GlobalJobFilters.Filters.Add(new ErrorReportingJobFilter());
This looks kool.
OnStateElection and OnPerformed doesn't work for me, because JobActivator.DisposeScope is called before OnStateElection/OnPerformed. Since I'm trying to resolve scoped dependency (CurrentAppContext) inside OnStateElection/OnPerformed I am getting the error:
System.InvalidOperationException: Scope was not available. Did you forget to call container.BeginScope()?
in Castle.MicroKernel.Lifestyle.LifetimeScopeAccessor.GetScope(CreationContext context)
I need to write some application variables from CurrentAppContext into the log.
Hangfire writes job's exceptions as WARN, not ERROR into the log. So how can I handle job exceptions inside DI/IoC scope?
Most helpful comment
I'm not sure about the hook thing, but you can manage exceptions in jobs using a JobFilter, and then reporting the exception to the external service.
and then register the Job filter globally
GlobalJobFilters.Filters.Add(new ErrorReportingJobFilter());