Error Handling in Azure Functions
Learn how to handle errors in Azure Functions so they don’t cause serious system failures.
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
Exception handling
The most obvious way to handle errors is to enable exception handling in the code. Just like in any C# code, we can wrap our logic in a try
block, as we do in line 12 ...