Fail A Job Without Throwing An Exception

I’m doing a Fire-and-Forget method invocation like this.

BackgroundJob.Enqueue(() => SendEmail(name));

I want to fail the job inside the SendEmail() method.
Because since all the probable exceptions are handled in my code, even if an exception occurs in the job method, the result of the job will be ‘Successful’. Because the exception is handled.

How to force to Fail a Job?. According to the above topic we have to throw an exception in order to fail a job. Is there any other way to do this?

Not that I’m aware of, but I’m curious what the aversion is to not trapping your Exceptions that happen and just allowing those to fail the job?

1 Like

I have to catch the exception and do some things inside the catch, That’s why, not trapping the Exceptions is not a solution.

So the only solution would be to throw the exception again inside the catch.

Sure, that seems reasonable though. Do what you need then:

catch (SomeException e)
  // do stuff

throw; is not much different than job.Fail = true; or something, right?

1 Like

Yes exactly. Thanks for the reply @leviwilson

And it is totally correct how Hangfire works here. If the exception is handled, the Job shouldn’t be failed.

I have a special situation here, I’m using a WPF app, I’m running Hangfire server in the WPF app like a Windows Service or Console app,

I can queue the jobs and run but when a job is failure by an exception anything like loss connection to internet or something the app crash, I can’t catch the exception because I tried to mark the job as failure but this unhandled exception and the app crash and close, I tried to use AttempRetries attribute but Hangfire is not able to catch the exception

I know it’s been a long time but just to add to the mix, I have a situation in which job.Fail = true would be massively different than throw;

I have a hangfire running on a separate thread of an website. This morning we had a job failing (and throwing) and it brought the whole website down.

The reason why can be seen here:

Our previous policy was to handle all exceptions, send the team an email and re-throw so the job the can retry but because of the above we will be forced to have a failed job finished as successful.

Hi Valdernir,

I found I was getting the same issue running my code from VS. I found changing the return type from void to Task has resolved the issue.