gpt4 book ai didi

c# - 如何记录我的 Web API 项目中依赖项解析期间抛出的异常?

转载 作者:行者123 更新时间:2023-11-30 14:11:07 27 4
gpt4 key购买 nike

如果 Controller 的依赖项解析失败,如何设置 IIS 中托管的 Web API 2(版本 5)项目以记录错误?我正在为 DI 使用 Autofac Web API 2 集成(3.1 版)。

在我的 Global.asax.cs 中,我有以下内容:

public class Global : HttpApplication {
protected void Application_Start() {
var resolver = new AutofacWebApiDependencyResolver(_container);
GlobalConfiguration.Configuration.DependencyResolver = resolver;

// other initialization

GlobalConfiguration.Configuration.EnsureInitialized();

}

protected void Application_Error(Object sender, EventArgs e){
Exception exception = Server.GetLastError();
if (exception != null) {
_log.Error("Application error", exception);
}
}
}

在使用 AutofacDependencyResolver 的类似 MVC 项目中,这足以记录当 Autofac 在创建 Controller 时无法解析依赖项时抛出的 Autofac.Core.DependencyResolutionException,但在我的 Web API 项目这似乎不起作用,要么没有抛出异常,要么我没有设置正确的日志记录处理程序。相反,不会记录任何消息,而是将 500 响应返回给客户端。

如果在依赖解析期间没有抛出错误(我的模块设置正确)那么一切正常, Controller 被解析并按预期处理请求。

我还设置了一些其他异常记录器,它们也不记录此异常:

  • 处理未处理的异常事件:AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException(在 Global.asax.cs 中)
  • 设置派生自 ExceptionFilterAttribute 的异常日志记录过滤器。这会记录在 Controller 处理请求时抛出的异常,但不会记录在依赖项解析期间抛出的异常。

最佳答案

这可以在 Web API 2.1 中通过使用新的 Global Error Handling 来完成。 .

public class Log4NetExceptionLogger : ExceptionLogger {
private static readonly ILog _log = LogManager.GetLogger("{your logger name here}");
public override void Log(ExceptionLoggerContext context) {
if (context == null) {
throw new ArgumentNullException("context");
}
// When the framework calls an exception logger or an exception handler, it will always provide an Exception and a Request.
// http://aspnetwebstack.codeplex.com/wikipage?title=Global%20Error%20Handling&referringTitle=Specs
if (context.Exception == null) {
throw new ArgumentException("context.Exception is null", "context");
}
if (context.Request == null) {
throw new ArgumentException("context.Request is null", "context");
}

_log.Error(context.Request, context.Exception);
}
}

// In GlobalConfiguration setup in Global.asax.cs
config.Services.Add(typeof(IExceptionLogger), new Log4NetExceptionLogger());

关于c# - 如何记录我的 Web API 项目中依赖项解析期间抛出的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21194802/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com