所以我有一个全局错误处理程序,只要我的应用程序出现错误,它就会发送电子邮件。这很好用,但是,有一些错误(即可怕的“对象引用未设置到对象的实例”错误)非常难以跟踪。我有一个简洁的函数,可以将序列化模型转换为字符串,这样我实际上可以看到有问题的代码行正在处理的数据,但我想知道有没有一种方法可以让我在应用程序中捕获模型级别错误处理程序?我得到了我需要的一切,即 url、堆栈跟踪等,只是看不到当前正在处理的数据。以下是我的 Application_Error 中当前的内容:
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
HttpContext con = HttpContext.Current;
string serverUrl = "";
if (con.Request != null)
{
serverUrl = con.Request.Url.ToString();
}
var user = "";
if (GlobalSiteData.CurrentUser != null) user = GlobalSiteData.CurrentUser.Username;
var ip = (Request.UserHostAddress == null ? "" : Request.UserHostAddress.ToString());
try {
Mailers.UserMailer mailer = new Mailers.UserMailer();
ErrorLog elog = new ErrorLog
{
ErrorDate = DateTime.Now,
InnerException = (exception.InnerException == null ? "" : exception.InnerException.Message),
Message = exception.Message,
UserName = user,
Source = exception.TargetSite.Name,
SourceUrl = serverUrl,
StackTrace = exception.StackTrace,
IPAddr = ip
};
mailer.LogEntry(elog).Send();
ErrorHelpers.LogErrorToFile(elog);
}
catch (Exception ex)
{
string err = ex.Message;
}
}
最佳答案
如果这是一个 MVC 应用程序,那么我建议您使用错误处理程序。这样你就可以访问filterContext,它应该包含你需要的一切。
在 Global.asax 或 AppStart 文件夹中的 FilterConfig.cs 中注册以下行。
filters.Add(new CustomHandleErrorAttribute());
创建以下类并添加您需要的日志记录。这应该记录 MVC 框架内发生的所有异常。在 MVC 框架之外,有些情况是无法捕获的,但在大多数情况下,这应该是第一道防线。我将链接另一个使用 MVC Controller 上可用的 OnException 方法的选项。
public class CustomHandleErrorAttribute: HandleErrorAttribute {
public override void OnException(ExceptionContext filterContext)
{
if (filterContext.Exception != null)
{
// do something
}
base.OnException(filterContext);
}
}
这是另一种错误处理方法,也仅适用于 MVC。
http://blog.dantup.com/2009/04/aspnet-mvc-handleerror-attribute-custom.html
关于c# - 在Application_Error中获取当前模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26226028/