Just in Chronicles

Life as a Voyage

How to Save Log While Handling Error in ASP.NET MVC 2

leave a comment »

The built-in Error.aspx page provided by ASP.NET MVC 2 is pretty convenient as developers don’t need to worry about handling an error when it occurs. However, the page is just displaying “THERE IS AN ERROR!”, not anything else. Typically developers and their clients want to know why errors have occurred, but also don’t want to expose the error details to general public. In order to achieve this, error logging to a text file or database is commonly used.

The Error.aspx page has a model instance typed System.Web.Mvc.HandleErrorInfo. As soon as an error comes up while processing data in a controller, if the action gets the [HandleError] attribute set, the error object is immediately thrown to the model. So, error saving function should be implemented before the exception is thrown to the model.

First of all, we need to prepare a base controller class inherited from System.Web.Mvc.Controller.

[HandleError]
public abstract class BaseController : Controller
{
	protected string BaseUrl { get; private set; }
	protected string PublicUrl { get; private set; }

	public BaseController()
	{
	}

	[HandleError]
	protected override void OnException(ExceptionContext filterContext)
	{
		base.OnException(filterContext);

		this.SaveLog(filterContext.Exception);
	}

	[HandleError]
	private void SaveLog(Exception e)
	{
		using (StreamWriter sw = File.AppendText(System.Web.HttpContext.Current.Server.MapPath("~/logs/error/log-" + String.Format("{0:yyyy-MM-dd}", DateTime.Today) + ".txt")))
		{
			sw.WriteLine("--------- " + Convert.ToString(DateTime.Now) + " --------- --------- --------- --------- ---------");
			if (e != null)
			{
				sw.WriteLine("Message: " + e.Message);
				sw.WriteLine("Stack Trace: ");
				sw.WriteLine(e.StackTrace);
				sw.WriteLine("");
			}
			sw.Close();
		}
	}
}

Please note that the base controller overrides the OnException() method, which triggers when an exception is thrown. So, the overridden method will call the SaveLog() method. Within the SaveLog() method, you can whatever you want to do.

Advertisements

Written by Justin Yoo

30/06/2011 at 15:09

Posted in For .NET

Tagged with , , ,

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s