Error Handling in Azure Functions
Explore techniques to handle errors within Azure Functions, including exception handling and configuring retry policies for different bindings. Understand how to log exceptions, control retries through host policies, and improve function reliability and availability.
We'll cover the following...
We'll cover the following...
While Azure infrastructure is capable of dealing with the failures in the function app host, it’s up to us to handle the errors inside the functions. This is what we will cover in this lesson. We will do so with the help of the interactive playground below, which contains various examples of how we can handle errors:
using System;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
namespace AzureFunctionApp;
public class Functions
{
[FunctionName("TimerWithExceptionHandling")]
public void TimerWithExceptionHandling([TimerTrigger("0 * * * * *")] TimerInfo timer, ILogger log)
{
try
{
if (DateTime.UtcNow.Minute % 5 == 0)
throw new InvalidOperationException("Incorrect schedule time.");
}
catch(Exception ex)
{
log.LogError("Timer execution failed. {Error}", ex.Message);
}
log.LogInformation("Timer executed successfully. Next occurrence: {Occurrence}", timer.Schedule.GetNextOccurrence(DateTime.UtcNow));
}
[FunctionName("TimerWithRetries")]
[FixedDelayRetry(5, "00:00:05")]
public void TimerWithRetries([TimerTrigger("0 * * * * *")] TimerInfo timer, ILogger log)
{
if (DateTime.UtcNow.Minute % 5 == 0)
throw new InvalidOperationException("Incorrect schedule time.");
log.LogInformation("Timer executed successfully. Next occurrence: {Occurrence}", timer.Schedule.GetNextOccurrence(DateTime.UtcNow));
}
}Function app with error handling
...