Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading