How can I manually fail an Azure Function?

Description: I have an Azure Function on a timer trigger that performs multiple steps. Each step has its own try/catch block to swallow any exceptions and log them. These steps are not dependent on each other, therefore I do not want an exception to stop the entire function.

try { await StepOneAsync(); }
catch (Exception ex) { logger.LogError(ex, "Step one failed"); }

try { await StepTwoAsync(); }
catch (Exception ex) { logger.LogError(ex, "Step two failed"); }

Problem: If step 1 fails, I do want Azure to consider the function as a failure so we can still receive built-in alerts and see the failure in the invocations. How can I manually flag the function as failed after the steps have ran?

Attempted solution: I have added flags for each step, and if any step failed I throw an exception at the end.

var stepOneSucceeded = false;
try 
{ 
    await StepOneAsync(); 
    stepOneSucceeded = true;
}
catch (Exception ex) { logger.LogError(ex, "Step one failed"); }

var stepTwoSucceeded = false;
try 
{ 
    await StepTwoAsync(); 
    stepTwoSucceeded = true;
}
catch (Exception ex) { logger.LogError(ex, "Step two failed"); }

if (!stepOneSucceeded || !stepTwoSucceeded) throw new Exception("Steps failed");

However this is a made-up exception just to trigger the function to fail and appears to be a work around.

>Solution :

Instead of using a boolean flag and throwing a new exception, store the real exception and re-throw it:

Exception exceptionOccured = null;

try
{
    await StepOneAsync();
}
catch (Exception ex)
{
    exceptionOccured = ex;
}

try
{
    await StepTwoAsync();
}
catch (Exception ex)
{
    exceptionOccured = ex;
}

if (exceptionOccured != null)
{
    throw new Exception("Something went wrong", exceptionOccured);
}

Leave a Reply