C# WebJob和ExceptionFilterAttribute
我为我的web api应用程序使用ExceptionFilterAttribute来捕获不同的未处理异常,即:C# WebJob和ExceptionFilterAttribute,c#,exception,exception-handling,attributes,azure-webjobs,C#,Exception,Exception Handling,Attributes,Azure Webjobs,我为我的web api应用程序使用ExceptionFilterAttribute来捕获不同的未处理异常,即: public class InvalidDriverExceptionAttribute : ExceptionFilterAttribute { public override void OnException(HttpActionExecutedContext actionExecutedContext) { if (actionExecutedCo
public class InvalidDriverExceptionAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
if (actionExecutedContext.Exception != null)
{
if (actionExecutedContext.Exception is Domain.InvalidDriverException)
{
var resp = actionExecutedContext.Request.CreateErrorResponse(HttpStatusCode.NotFound, "User is not a driver");
actionExecutedContext.Response = resp;
}
}
//base.OnException(actionExecutedContext);
}
}
但我希望我的网络工作有类似的引擎。可能吗
但我希望我的网络工作有类似的引擎。可能吗
对。但是,由于web作业是连续的或有计划的,所以它们的实现方式存在一些差异。您可以使用ErrorTrigger来实现您的目标。一种错误触发器,允许您对发生错误时运行时自动调用的函数进行注释。它可以在执行web作业时监视其中的错误。我的演示结果如下:。有关更多详细信息,请参阅此
在使用Azure WebJob开发作业时,最好实施错误监控,以防作业执行时出现问题
WebJobs ErrorTrigger扩展是核心扩展的一部分,它将帮助我们实现这一点
我已经从FunctionExceptionFilterAttribute创建了派生类
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);
}
}
}
然后将其用于方法:
[NoAutomaticTrigger]
[ErrorHandler]
public async Task GetDriversAsync(TextWriter logger)
{
当异常发生时,它调用此代码并向我发送通知电子邮件