Best way of handling timeouts with AsyncController

▼魔方 西西 提交于 2019-12-06 10:13:25

问题


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.



来源:https://stackoverflow.com/questions/9600530/best-way-of-handling-timeouts-with-asynccontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!