Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 718
Alex Marshall Avatar asked Mar 10 '16 22:03

Alex Marshall


2 Answers

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:

  • Dependency injection using Azure WebJobs SDK?
like image 195
Thomas Avatar answered Nov 13 '22 20:11

Thomas


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(); 
} 
like image 39
Stephen Reindl Avatar answered Nov 13 '22 20:11

Stephen Reindl