Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# attribute to surround with try - catch

I find myself writing methods with try{stuff}catch(Exception e){log, other stuff} quit a bit, so I was trying to figure out how to make an attribute to help me out. I've checked out the following threads pretty extensively, and can't seem to get my implementation to work.

attribute does not seem to act at all

ASP.NET MVC Controller.OnException not being called

.net Attributes that handle exceptions - usage on a property accessor

My top-level web.config is set to

<customErrors mode="On" defaultRedirect="/error.html"/>

and I'm compiling in not-debug mode. My attribute is below :

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class SafeWebMethodAttribute: ActionFilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        filterContext.ThrowIfNull();

        if (filterContext.ExceptionHandled)
        {
            return;
        }
        Log.LogException(filterContext.Exception);
        filterContext.HttpContext.Response.StatusCode = 500;
        filterContext.HttpContext.Response.Write(filterContext.Exception);
        filterContext.ExceptionHandled = true;
    }
}

and I'm calling it here -

public class Test : Controller
{
    [SafeWebMethod]
    public ActionResult Test()
    {
        throw new ArgumentException("test");
    }
}

I can't seem to get a breakpoint hit in the attribute, or if I change the status code to get it to show up.

I've also copied the code from the [HandleError] attribute, and can't get a breakpoint in there either, so I think it is something wrong with my configuration, but I can't figure out what.

Any thoughts or ideas would be greatly appreciated

like image 893
hermitt Avatar asked Mar 13 '12 04:03

hermitt


1 Answers

Going from the link you provided .net Attributes that handle exceptions - usage on a property accessor what you want is not possible (see implementation in Aaronaught second code snippet).

Unless you use some kind of aspect framework you would have to implement the code that checks for the presenc of the attribute and acts on it on your own, and run that code in every catch(...) statement.

The idea you had was great, and I might use it in a framework on my own, but the constraint still holds that you have to implement it on your own.

hth

Mario

like image 183
Mario The Spoon Avatar answered Oct 24 '22 22:10

Mario The Spoon