Click here to Skip to main content
15,892,965 members
Articles / Web Development / ASP.NET

Handling Error Centrally in a SharePoint Application

Rate me:
Please Sign up or sign in to vote.
4.21/5 (11 votes)
20 May 2008CPOL4 min read 85K   596   22  
An article on handling errors centrally in a SharePoint application, using IHttpModule.
using System;
using System.Web;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Web.UI;
using Microsoft.Practices.EnterpriseLibrary.Logging;

namespace CentralErrorHandler
{
    public class ErrorModule : IHttpModule
    {
        #region IHttpModule Members

        public void Dispose()
        {
            //throw new Exception("The method or operation is not implemented.");
        }

        public void Init(HttpApplication Context)
        {
            Context.Error += new EventHandler(Application_Error);
        }

        #endregion


        public void Application_Error(object sender, EventArgs e)
        {            
            HttpContext Context = HttpContext.Current;            
            Exception exception;
            for (exception = Context.Server.GetLastError(); exception.InnerException != null; exception = exception.InnerException) { }

            String code = DateTime.Now.ToString("ddMMyyyy-HHmmfff");
            String Message = exception.Message + Environment.NewLine + "Stack Trace: " + exception.StackTrace;

            Logger.Write(Message, "General",5, 1, System.Diagnostics.TraceEventType.Critical, code);  
            
            HttpContext.Current.Application.Add("ErrorCode", code);
            HttpContext.Current.Application.Add("LastException", exception);

            String CustomErrorPagePath = System.Configuration.ConfigurationManager.AppSettings["CustomErrorPagePath"];

            ((System.Web.HttpApplication)(sender)).Response.Redirect(CustomErrorPagePath);
        }



    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Gen-i, Australia
Australia Australia
Expertise area: ASP.NET, C#, Microsoft Office SharePoint 2010 & 2007, Web Service, Windows-based Applications etc.

Blog: http://mydevdiary.blogspot.com/

Comments and Discussions