Conditional Error Handling on Final Retry of Task

I’m attempting to make changes in our base error handler to check whether this execution was the final retry on a task before executing certain error handling code. Our tasks have a variable amount of retries depending on the resources consumed during their execution.

It’s easy enough to get the retry count on the from the ServerExceptionContext but I’m not seeing any way to get the maximum retry attempts for a task. Is there one? Or is there some other value I can hang the condition on?

I’ve got a bit of a wonky solution using the BackgroundJob reflection data.

var maxAttemptCount = filterContext.BackgroundJob.Job.Method
	.CustomAttributes.FirstOrDefault(x => x.AttributeType.IsInstanceOfType(typeof(AutomaticRetryAttribute)))
	?.NamedArguments?.FirstOrDefault(x => x.MemberName.Equals("Attempts"))
	.TypedValue.Value as int? ?? 0;