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 ?
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:
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With