zach zach - 1 year ago 104
C# Question

Get current model in Application_Error

so I have a global error handler that sends an email whenever I get an error in my app. This works great, however, there are some errors (i.e. the dreaded "Object reference not set to an instance of an object" error) that are extremely difficult to trace. I have a neat function that will convert a serialized model into a string for me so I can actually see the data the offending line of code is dealing with, but what I was wondering is there a way for me to capture the model in an application level error handler? I'm getting everything else I need, i.e. url, stack trace, etc, just no visibility to the data currently being handled. Here is what I have currently in my 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
catch (Exception ex)
string err = ex.Message;

Answer Source

If this is an MVC Application then I would recommend you use an error handler. That way you have access to the filterContext which should have everything you need in it.

Register the following line in the global.asax or in the FilterConfig.cs in the AppStart folder.

filters.Add(new CustomHandleErrorAttribute());

Create the following class an add the logging that you need. This should log all exceptions that happen within the MVC framework. There are conditions outside of the MVC framework that this won't catch but for the most part this should be the first line of defense. I'll link another option that uses the OnException method that's available on MVC Controllers.

   public class CustomHandleErrorAttribute: HandleErrorAttribute {

      public override void OnException(ExceptionContext filterContext)
          if (filterContext.Exception != null)
            // do something


Here's an another error handling method that's also only for MVC.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download