[RESOLVED]Log custom errors

I found some code on the web that should help me log custom errors but can’t figure out how to use it,  it won’t fire.  (I don’t want to install Elmah right now because I’m running some tests as a learning experience).  Running this with F5 throws an exception
in the Action/Method (divide by zero error), running it with control F5 shows standard error page, but in neither case am I able to write to the debug file. 

using System.IO;

[HttpPost]
[HandleError]
[HandleErrorAndLogExceptionAttribute]
public ActionResult Index(string donothing) {
int x = 0;
int y = 5 / x;  //divide by zero
return View();
}

        private static StreamWriter sw = null;

        public static void writeError(string err) {
            if (sw == null) {
                //Loop through existing debug filenames to
                //find a new filename to create. 
                int num = 0;
                while (true) {
                    string dest = "H:\Debug-" + num.ToString() + ".txt";
                    if (System.IO.File.Exists(dest)) continue;
                    sw = new StreamWriter(dest);
                    sw.AutoFlush = true;
                }
            }
            sw.WriteLine(err);
        }

        public class HandleErrorAndLogExceptionAttribute : FilterAttribute, IExceptionFilter {
            public void OnException(ExceptionContext filterContext) {
                writeError("error at " + DateTime.Now.ToString()); //won't execute. 
//code below omitted for brevity
} }

Maybe my class definition is wrong. Here’s a second one I tried but still doesn’t work:

 public class HandleErrorAndLogExceptionAttribute : HandleErrorAttribute, IExceptionFilter {
            public override void OnException(ExceptionContext filterContext) {
                writeError("error at " + DateTime.Now.ToString()); //won't execute. 
            }
        }

Well it was an infiite loop, fixed that but still not working

This code seems to be working, still testing…

        [HttpPost]
        [HandleErrorAndLogExceptionAttribute]
         public ActionResult Index(string donothing) {
            int x = 0;
            int y = 5 / x;
            return View();
        }
        public class HandleErrorAndLogExceptionAttribute : FilterAttribute, IExceptionFilter {
            public void OnException(ExceptionContext filterContext) {
                MvcApplication.writeError("error at " + DateTime.Now.ToString()); //won't execute. 
                //code below omitted for brevity
            }
        }

The code above is working now but what I found especially helpful was this article:

http://www.crafted.co.uk/latest/blog/custom-errors-in-asp-net-mvc

Leave a Reply