【发布时间】:2020-03-02 04:49:36
【问题描述】:
我有一个简单的 C# Web Api 项目,它提供了一些安静的端点。
控制器致命的服务器错误处理/记录通常可以通过以下方式很好地描述:
- 在 Global.asax.cs 中实现/覆盖 Application_Error 方法
protected override void Application_Error(object sender, EventArgs e)
{
var ex = Server.GetLastError();
_logger.Error("Unexpected error while initializing application", ex);
}
- 或者通过添加异常处理过滤器:
config.Filters.Add(new ExceptionHandlingAttribute());
或
GlobalConfiguration.Configuration.Filters.Add(new ExceptionHandlingAttribute());
public class ExceptionHandlingAttribute : ExceptionFilterAttribute
{
private static readonly ILog _logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
_logger.Error("Unexpected error in API.", actionExecutedContext.Exception);
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent("An error occurred, please try again or contact the administrator."),
ReasonPhrase = "Critical Exception"
});
}
}
但是,当控制器的实例化过程中由于此代码的构造函数中的依赖注入失败而发生错误时:
public class DataController : ApiController
{
private readonly IDataService _dataService;
public DataController(IDataService dataService)
{
_dataService = dataService;
}
[AllowAnonymous]
[HttpGet]
public IHttpActionResult GetSomeStuff()
{
return Ok(new AjaxResponse("somestuff"));
}
以上方法都没有捕捉到错误。我怎样才能发现这些错误?
【问题讨论】:
标签: c# .net asp.net-mvc-4 asp.net-web-api