在Katana (OWIN)实现中实现全局异常捕获处理程序的正确方法是什么?
在作为Azure Cloud服务(worker角色)运行的自托管OWIN/Katana实现中,我将此代码放在中间件中:
throw new Exception("pooo");然后,我将这些代码放在Startup配置方法中,在事件处理程序中设置一个断点:
AppDomain.CurrentDomain.UnhandledException +=
CurrentDomain_UnhandledExceptionEventHandler;以及同一类中的事件处理程序(第一行设置了一个断点):
private static void CurrentDomain_UnhandledExceptionEventHandler(object sender, UnhandledExceptionEventArgs e)
{
var exception = (Exception)e.ExceptionObject;
Trace.WriteLine(exception.Message);
Trace.WriteLine(exception.StackTrace);
Trace.WriteLine(exception.InnerException.Message);
}当代码运行时,不会命中断点。但是,Visual输出窗口确实包括此内容:
A first chance exception of type 'System.Exception' occurred in redacted.dll
A first chance exception of type 'System.Exception' occurred in mscorlib.dll我还尝试将连线和处理程序移动到Worker角色OnStart方法,但仍然没有命中断点。
我根本没有使用WebAPI,但是看了关于在那里做什么的文章,但是我没有发现任何明确的东西,所以我在这里
运行在.NET框架4.5.2上,相对于2013年。
所有的想法都受到赞赏。谢谢。
发布于 2018-05-02 04:41:09
试试这个:
public class CustomExceptionHandler : IExceptionHandler
{
public Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)
{
// Perform some form of logging
context.Result = new ResponseMessageResult(new HttpResponseMessage
{
Content = new StringContent("An unexpected error occurred"),
StatusCode = HttpStatusCode.InternalServerError
});
return Task.FromResult(0);
}
}在启动时:
public void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration();
config.Services.Replace(typeof(IExceptionHandler), new CustomExceptionHandler());
}发布于 2019-10-04 08:44:36
可以使用自定义异常筛选器属性。
public static class WebApiConfiguration
{
public static void Register(HttpConfiguration config)
{
config.RegisterExceptionFilters();
}
}
public static class HttpConfigurationFilterExtensions
{
public static HttpConfiguration RegisterExceptionFilters(this HttpConfiguration httpConfig)
{
httpConfig.Filters.Add(new CustomExceptionFilterAttribute());
return httpConfig;
}
}
public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
if (context.Exception is CustomException)
{
context.Response = new HttpResponseMessage((HttpStatusCode)CustomHttpStatusCode.CustomCode);
}
}
}
public class CustomException : Exception
{
public CustomException(string message)
: base(message)
{
}
}https://stackoverflow.com/questions/30918649
复制相似问题