Fail A Job Without Throwing An Exception

job-filters
sql-server
Tags: #<Tag:0x00007f499a5a3d50> #<Tag:0x00007f499a5a3be8>

#1

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?


#2

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?


#3

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.


#4

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

catch (SomeException e)
{
  // do stuff
  throw;
}

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


#5

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.


#6

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


#7

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 asp.net website. This morning we had a job failing (and throwing) and it brought the whole website down.

The reason why can be seen here: https://blogs.msdn.microsoft.com/tess/2006/04/27/asp-net-2-0-crash-case-study-unhandled-exceptions/

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.