Search code examples
asp.net-mvcasp.net-mvc-filters

Get action local variables name and value OnException customized filter


Want to retrieve the variable value of action into customized filter

  public class TrackError : IExceptionFilter
            {
              public void OnException(ExceptionContext filterContext)
                {
                    // How to get the value of X ?????????????????                   
                }
        }

Controller :

[TrackError]
public class HomeController : Controller
    {

        public ActionResult Index()
        {

                int x = 0;

            throw new Exception("XYZ");
            return View();
        }
    }

Solution

  • Create custom exception and put whatever additional data you need into its properties. Then you catch that exception type in one of your catch blocks within your exception filter.

    public class ServiceException : Exception, ISerializable
    {
            public WhateverType X {get;set;}
            public string Message{get;set;}
    
            public ServiceException()
            {
                // Add implementation.
            }
    
            public ServiceException(WhateverType x, string message)
            {
                this.X = x;
                this.Message = message;
            }
    
            public ServiceException(string message):base(message)
            {
            }
    
            public ServiceException(string message, Exception inner)
            {
                // Add implementation.
            }
    
            // This constructor is needed for serialization.
            protected ServiceException(SerializationInfo info, StreamingContext context)
            {
                // Add implementation.
            }
    }
    

    and then in filter:

    public override void OnException(HttpActionExecutedContext context)
            {
                if (context.Exception is ServiceException)
                {
                 //Here you can access (context.Exception as ServiceException).X
                }
    }
    

    throw your exception like:

    throw new ServiceException(X, "Your custom message gore here");