Can I run every ContentResult in the controller using universal try / catch elegantly?

I guess there is an elegant way to do this, but I don't know what it is. In the application I'm working on, I have many ContentResults that return xml. Each action that returns xml goes through the same try / catch block, and I repeat over and over - here is an example of what I'm talking about:

public ContentResult SomeAction()
{
    try
    {
        //some stuff here
    }
    catch(Exception ex) 
    { 
        HandleErrorMethod(ex);
    }
    return this.Content(someObject.ToXmlString(), contentReturnType);
}        

This happens 3-4 times in the controller, so I believe that I can either draw it using an attribute, or run some method in global.asax or something like this, so as not to repeat myself again and again - without saying already about code changes in the future. I really don't know where to look (I suppose that's why I ask); Thank!

+3
2

ActionFilterAttribute :

public class XmlExceptionAttribute : ActionFilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        if (filterContext.Exception == null) return;

        var response = filterContext.Controller.ControllerContext.HttpContext.Response;
        response.ContentType = "text/xml";
        response.Write((new Status(filterContext.Exception)).ToXmlString());
    }
}

, , , :

[HttpGet]
[XmlException]
public ContentResult Logout(string sessionIdStr)
{
    // do stuff
    // throw exceptions if I need to, they will be handled
    return this.Content(status.ToXmlString(), contentReturnType);
}
+1

. Controller.OnException, -, JavaScrpt .

HandleError, , .

protected override void OnException(ExceptionContext filterContext)
{

if (filterContext == null)
        return;

var ex = filterContext.Exception; //Your exception
//Now put the rest of your code that is currently in your handle error method. 
}

[HandleError]
public ContentResult SomeAction()
{
   //some stuff here
   return this.Content(someObject.ToXmlString(), contentReturnType);
}   
+3

Source: https://habr.com/ru/post/1795317/


All Articles