Best way of handling timeouts with AsyncController

2019-04-13 15:29发布

问题:

I have a long time polling controller in my MVC3 project. It has its timeout set to 30 seconds. I have a HandleErrorAttribute implementation that handles logging of all errors.

Since the timout throws a TimeoutException it means these will be presented in the log.

I need to intercept this error before my HandleErrorAttribute class gets it and return a json object instead of the 500 error page. Whats the best approach for this?

I did this and it works

public class HandleTimeout : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        if(filterContext.Exception is TimeoutException)
        {
            filterContext.Result = new { Timeout = true }.AsJson();
            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.StatusCode = 200;
        }

        base.OnException(filterContext);
    }
}

Best approach?

回答1:

I went with this route, the difference from my above code is that I also check if the Controller is Async, because we only want to handle Timeouts in this fashion if we are in a long time polling scenarios.

public class HandleTimeout : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        if(filterContext.Exception is TimeoutException && filterContext.Controller is AsyncController)
        {
            filterContext.HttpContext.Response.StatusCode = 200;
            filterContext.Result = new { Timeout = true }.AsJson();
            filterContext.ExceptionHandled = true;
        }

        base.OnException(filterContext);
    }
} 


回答2:

The notion of best is very subjective. I prefer not to talk about it as different people have different definition of it. For me using a custom exception filter is a very good approach to handle this case without polluting your controller with exception handling code.