Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 261997
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T22:28:44+00:00 2026-05-11T22:28:44+00:00

I am looking for a simple solution to do Exception Logging combined with Error

  • 0

I am looking for a simple solution to do Exception Logging combined with Error Handling in my ASP.Net MVC 1.0 application.

I’ve read lots of articles, including Questions posted here on StackOverflow, which all provide varying solutions for different situations. I am still unable to come up with a solution that suits my needs.

Here are my requirements:

  1. To be able to use the [HandleError] attribute (or something equivalent) on my Controller, to handle all exceptions that could be thrown from any of the Actions or Views. This should handle all exceptions that were not handled specifically on any of the Actions (as described in point 2). I would like to be able to specify which View a user must be redirected to in error cases, for all actions in the Controller.

  2. I want to be able to specify the [HandleError] attribute (or something equivalent) at the top of specific Actions to catch specific exceptions and redirect users to a View appropriate to the exception. All other exceptions must still be handled by the [HandleError] attribute on the Controller.

  3. In both cases above, I want the exceptions to be logged using log4net (or any other logging library).

How do I go about achieving the above? I’ve read about making all my Controllers inherit from a base controller which overrides the OnException method, and wherein I do my logging. However this will mess around with redirecting users to the appropriate Views, or make it messy.

I’ve read about writing my own Filter Action which implements IExceptionFilter to handle this, but this will conflict with the [HandleError] attribute.

So far, my thoughts are that the best solution is to write my own attribute that inherits from HandleErrorAttribute. That way I get all the functionality of [HandleError], and can add my own log4net logging. The solution is as follows:

    public class HandleErrorsAttribute: HandleErrorAttribute {

      private log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

      public override void OnException(ExceptionContext filterContext)
      {
          if (filterContext.Exception != null)
          {
            log.Error("Error in Controller", filterContext.Exception);
          }

          base.OnException(filterContext);
      }
   }

Will the above code work for my requirements? If not, what solution does fulfill my requirements?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-11T22:28:44+00:00Added an answer on May 11, 2026 at 10:28 pm

    I’m still a bit confused with all the different solutions out there, and how attributes can interfere with each other, but I went with this solution:

    public class LogErrorsAttribute: FilterAttribute, IExceptionFilter
    {
        #region IExceptionFilter Members
    
        void IExceptionFilter.OnException(ExceptionContext filterContext)
        {
            if (filterContext != null && filterContext.Exception != null)
            {
                string controller = filterContext.RouteData.Values["controller"].ToString();
                string action = filterContext.RouteData.Values["action"].ToString();
                string loggerName = string.Format("{0}Controller.{1}", controller, action);
    
                log4net.LogManager.GetLogger(loggerName).Error(string.Empty, filterContext.Exception);
            }
    
        }
    
        #endregion
    }
    

    I still use the [HandleError] attribute as explained in the original question, and I just decorate each controller with a [LogErrors] attribute.

    This works for me, as it keeps the error logging in one place and doesn’t cause duplicate exceptions to be logged multiple times (which will happen if I extend [HandleError] and use the attribute in multiple places).

    I don’t think it will be possible to combine both the Exception Logging and Error Handling into one atrribute or class, without it becoming very tedious and complex, or affecting the use of [HandleError]

    But this works for me since I decorate each controller only once, with the [LogErrors] attribute, and decorate Controllers and Actions with [HandleError] exactly how I want to, without them interfering with each other.

    Update:

    Here is an example of How I use it:

    [LogErrors(Order = 0)]
    [HandleError(Order = 99)]
    public class ContactController : Controller
    {
        public ActionResult Index()
        {
            return View(Views.Index);
        }
    
        public ActionResult Directions()
        {
            return View(Views.Directions);
        }
    
    
        public ActionResult ContactForm()
        {
            FormContactMessage formContactMessage = new FormContactMessage();
    
            return View(Views.ContactForm,formContactMessage);
        }
    
        [HandleError(ExceptionType = typeof(SmtpException), View = "MessageFailed", Order = 1)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ContactForm(FormContactMessage formContactMessage)
        {
            if (ModelState.IsValid)
            {
                if (formContactMessage.IsValid)
                {
                    SmtpClient client = new SmtpClient();
    
                    MailAddress recipientAddress = new MailAddress(Properties.Settings.Default.ContactFormRecipientEmailAddress);
                    MailAddress senderAddress = new MailAddress(Properties.Settings.Default.ContactFormSenderEmailAddress);
                    MailMessage mailMessage = formContactMessage.ToMailMessage(recipientAddress, senderAddress);
    
                    client.Send(mailMessage);
    
                    return View("MessageSent");
                }
                else
                {
                    ModelState.AddRuleViolations(formContactMessage.GetRuleViolations());
                }
            }
            return View(Views.ContactForm, formContactMessage);
        }
    
        private static class Views
        {
            public static string Index { get { return "Index"; } }
            public static string Directions { get { return "Directions"; } }
            public static string ContactForm { get { return "ContactForm"; } }
    
        }
    }
    

    In the above code, SmtpExceptions in the ContactForm action overload are handled in a very specific way – the user is presented with a ViewPage specific to failed sent messages, in this case it is called “MessageFailed” . All other exceptions are handled by the default behaviour of [HandleError]. Also note that logging of errors occurs first, followed by handling of errors. This is indicated by the following:

    [LogErrors(Order = 0)]
    [HandleError(Order = 99)]
    

    Update:

    There is an alternative solution to this, with a very good explanantion. I recommend reading through it to get a better understanding of the issues involved.

    ASP.NET MVC HandleError Attribute, Custom Error Pages and Logging Exceptions
    (Thanks to Scott Shepherd below, who provided the link in an answer below).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 172k
  • Answers 172k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer You are likely to want the Instrument Control Toolbox. May 12, 2026 at 2:29 pm
  • Editorial Team
    Editorial Team added an answer I would not use a regular expression for matching items… May 12, 2026 at 2:29 pm
  • Editorial Team
    Editorial Team added an answer Only when it is necessary to the program logic, such… May 12, 2026 at 2:29 pm

Related Questions

We've occasionally been getting problems whereby our long-running server processes (running on Windows Server
I want to kill a whole process tree. What is the best way to
This is probably a complex solution . I am looking for a simple operator
I am looking for a tool for semi-automatic XSLT generation. Given 2 XML files,

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.