背景
我正在为客户端开发API服务层,并且我被要求捕获并记录全局错误。如何为C#MVC4 WebAPI应用程序全局记录所有异常?
因此,尽管像一个未知的终结点(或行为)很容易通过使用ELMAH或通过添加像这样的Global.asax
处理:
protected void Application_Error()
{
Exception unhandledException = Server.GetLastError();
//do more stuff
}
。 。与路由无关的未处理的错误不会被记录。例如:
public class ReportController : ApiController
{
public int test()
{
var foo = Convert.ToInt32("a");//Will throw error but isn't logged!!
return foo;
}
}
我自己也尝试通过注册该过滤器全局设置[HandleError]
属性:
filters.Add(new HandleErrorAttribute());
但也不会记录所有的错误。
问题/疑问
如何截取喜欢通过调用/test
上面,这样我就可以登录他们产生一个错误?看起来这个答案应该是显而易见的,但我已经尝试了迄今为止我能想到的一切。
理想情况下,我想添加一些东西到错误日志记录中,例如请求用户的IP地址,日期,时间等等。我也希望能够在遇到错误时自动发送电子邮件给支持人员。所有这些我都可以做,只要我能在发生这些错误时拦截这些错误!
已解决!
感谢Darin Dimitrov,我接受了他的回答,我弄明白了。 WebAPI不会不是以与常规MVC控制器相同的方式处理错误。
这里是什么工作:
1)添加自定义过滤器,您的命名空间:
public class ExceptionHandlingAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
if (context.Exception is BusinessException)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent(context.Exception.Message),
ReasonPhrase = "Exception"
});
}
//Log Critical errors
Debug.WriteLine(context.Exception);
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent("An error occurred, please try again or contact the administrator."),
ReasonPhrase = "Critical Exception"
});
}
}
2)现在全球注册过滤器在WebApiConfig类:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{action}/{id}", new { id = RouteParameter.Optional });
config.Filters.Add(new ExceptionHandlingAttribute());
}
}
或你可以跳过注册,只是装饰一个单控制器与[ExceptionHandling]
属性。
我有同样的问题。未处理的异常会被捕获到异常过滤器属性中,但是当我抛出一个新的异常时,它不会被异常过滤器属性捕获,对此有什么想法? – daveBM 2013-11-05 11:54:02
未知的API控制器调用像http:// myhost/api/undefinedapicontroller错误仍未捕获。 Application_error和Exception过滤器代码不会被执行。如何抓住他们呢? – Andrus 2013-11-26 09:03:37
全局错误处理已添加到WebAPI v2.1。请参阅我的回复:http:// stackoverflow。com/questions/17449400/how-do-i-set-up -a-global-error-handler-in-webapi/21264726#21264726 – DarrellNorton 2014-01-21 17:13:35