skip to Main Content

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.

2

Answers


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

    var exceptionsOccured = new List<Exceptions>();
    
    try
    {
        await StepOneAsync();
    }
    catch (Exception ex)
    {
        exceptionsOccured.Add(ex);
    }
    
    try
    {
        await StepTwoAsync();
    }
    catch (Exception ex)
    {
        exceptionsOccured.Add(ex);
    }
    
    if (exceptionsOccured.Count > 0)
    {
        throw new AggregateException(exceptionsOccured);
    }
    
    Login or Signup to reply.
  2. Assign your exception to a higher scoped variable within the catch block, like this:

    Exception savedEx;
    
    ...
    
    catch(Exception ex) {
      savedEx = ex;
    }
    

    Then you can just throw it.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search