I want to release all objects if any exception or error occur in running webjob. How do I know if error occurred.Is there any error trigger working with webjob?
There could be two approaches to handle this:
1) Try/Catch method:- You may trigger a mail or any action in catch block. In catch block you can send the info of the exception you got to your mail account or may even write to any DB table or add it to any queue.
2) Function Filter:- You may user function filter which has function exception filter attribute that is called on any exception situation. You may find the details here: https://github.com/Azure/azure-webjobs-sdk/wiki/Function-Filters
Also their is a piece of code from where you can take the reference:
public class ErrorHandlerAttribute : FunctionExceptionFilterAttribute
{
public override async Task OnExceptionAsync(FunctionExceptionContext exceptionContext, CancellationToken cancellationToken)
{
string body = $"ErrorHandler called. Function '{exceptionContext.FunctionName}': {exceptionContext.FunctionInstanceId} failed. ";
CombineErrorWithAllInnerExceptions(exceptionContext.Exception, ref body);
string[] emailList = System.Configuration.ConfigurationManager.AppSettings["SendErrorEmails"].Split(';');
await SendEmail.SendErrorNotificationAsync("WebJob - Common Driver Error", body);
}
private void CombineErrorWithAllInnerExceptions(Exception ex, ref string error)
{
error += $"ExceptionMessage: '{ex.Message}'.";
if (ex is Domain.BadStatusCodeException)
{
error += $"Status code: {((Domain.BadStatusCodeException)ex).StatusCode}";
}
if (ex.InnerException != null)
{
error += $"InnerEx: ";
CombineErrorWithAllInnerExceptions(ex.InnerException, ref error);
}
} }
You may call it by decorating your method with "ErrorHandler" attribute. So, in case of any exception "OnExceptionAsync" function will be called.