Search code examples
c#azurewebjob

How to programmatically mark an Azure WebJob as failed?


Is there a way to mark a WebJob (triggered, not continuous) as failed, without throwing an exception? I need to check that certain conditions are true to mark the job as successful.


Solution

  • According to Azure WebJob SDK, Code from TriggeredFunctionExecutor class.

    public async Task<FunctionResult> TryExecuteAsync(TriggeredFunctionData input, CancellationToken cancellationToken)
    {
    
        IFunctionInstance instance = _instanceFactory.Create((TTriggerValue)input.TriggerValue, input.ParentId);
        IDelayedException exception = await _executor.TryExecuteAsync(instance, cancellationToken);
        FunctionResult result = exception != null ?
            new FunctionResult(exception.Exception)
    
            : new FunctionResult(true);
        return result;  
    }
    

    We know that the WebJobs status depends on whether your WebJob/Function is executed without any exceptions or not. We can't set the finial status of a running WebJob programmatically.

    I need to check that certain conditions are true to mark the job as successful.

    Throw an exception is the only way I found. Or you could store the webjob execute result in an additional place(For example, Azure Table Storage). We can get the current invocation id by ExecutionContext class. In your webjob, you could save the current invocation id and the status you wanted to an Azure Table Storage. You could query the status later if you needed from Azure Table Storage based on the invocation id.

    public static void ProcessQueueMessage([QueueTrigger("myqueue")] string message, ExecutionContext context, TextWriter log)
    {
        log.WriteLine(message);
        SaveStatusToTableStorage(context.InvocationId, "Fail/Success");
    }
    

    To use ExecutionContext as parameter, you need to install Azure WebJobs SDK Extensions using NuGet and invoke UserCore method before your run your WebJob.

    var config = new JobHostConfiguration();
    config.UseCore();
    var host = new JobHost(config);
    host.RunAndBlock();