Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a custom C# attributes to handle exceptions in a handler

Tags:

c#

I have created a custom atttribute class like this

    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
    public class AMemento : Attribute
    {

        public void method(){
        try {

        }
        catch (Exception) {

        }}
    }

and I am planning to use this custom attribute in a handler to catch any exceptions occur their as follows

    [AMemento]
    [Authorize]
    public JsonResult GetWeatherData()
    {
         //// code here which throw an exception
    }

I want to know the way to complete the custom attribute class to capture an exception thrown in GetWeatherData() handler. Is it possible to implement like a higher order function like in python ?

like image 324
Gayan Kalanamith Avatar asked Nov 10 '14 08:11

Gayan Kalanamith


1 Answers

Within the MVC framework there is the HandleErrorAttribute class. This you can extend and override the OnException method. A good example of this is the in the Elmah MVC project where they have a HandleErrorAttribute class.

This question also provides some example of HandleErrorAttribute, again in the context of ELMAH but it should be relatively obvious that in overriding OnException you can provide your custom exception logic for MVC actions.

like image 192
AlexC Avatar answered Oct 29 '22 17:10

AlexC