Alex Marshall
Alex Marshall

Reputation: 10312

How to intercept an Azure WebJob failure / exception

Currently in Azure when a a WebJob throws an exception, the exception gets caught and handled by the JobHost (somehow) and then logs the exception to the dashboard that's available through the blade of the Web App in which the webjob is hosted. Is there any way to intercept the error handling or override it so that I can plug in my Application Insights instance ?

Upvotes: 13

Views: 4913

Answers (2)

Thomas
Thomas

Reputation: 29522

You can use the Azure WebJobs SDK Extensions : there is an ErrorTrigger so that you can use to intercept unhandled exceptions :

public class UnhandledErrorTrigger : IDisposable
{
    private readonly TelemetryClient _telemetryClient;

    public UnhandledErrorTrigger(TelemetryClient telemetryClient)
    {
        _telemetryClient = telemetryClient;
    }              

    public void UnHandledException([ErrorTrigger("0:01:00", 1)] TraceFilter filter, TextWriter log)
    {
        foreach (var traceEvent in filter.Events)
        {
            _telemetryClient.TrackException(traceEvent.Exception);
        }

        // log the last detailed errors to the Dashboard
        log.WriteLine(filter.GetDetailedMessage(1));
    }

    public void Dispose()
    {
        _telemetryClient.Flush();
    }
}

To register the Error extensions, call config.UseCore() in your startup code :

private static void Main()
{
    var config = new JobHostConfiguration();
    config.UseCore();

    ...
    new JobHost(config).RunAndBlock();
}

So if you are using an IoC container, you can easily inject your TelemetryClient. To configure a job activator for the webjob you can look at this post:

Upvotes: 6

Stephen Reindl
Stephen Reindl

Reputation: 5819

Have a look at some azure docs here. You can attach a handler to the AppDomain handling unknown exceptions (taken from the link above):

AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; 

// ... 

private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) 
{ 
    ExceptionTelemetry excTelemetry = new ExceptionTelemetry((Exception)e.ExceptionObject); 
    excTelemetry.SeverityLevel = SeverityLevel.Critical; 
    excTelemetry.HandledAt = ExceptionHandledAt.Unhandled; 

    telemetryClient.TrackException(excTelemetry); 

    telemetryClient.Flush(); 
} 

Upvotes: 2

Related Questions