繁体   English   中英

ASP.NET异常处理:ExceptionFilterAttribute与覆盖ExecuteAsync

[英]ASP.NET Exception-Handling: ExceptionFilterAttribute vs Overwrite ExecuteAsync

在ASP.NET中,Microsoft建议我们使用ExceptionFilterAttribute来处理异常。 异常过滤器

但是我认为我们还有其他方法可以处理它。 但是我不确定这些东西之间有什么区别:

  • 我们为什么不应该使用这种方式?

例如:我可以通过覆盖Controller类的ExecuteAsync来处理:

public class BaseController : ApiController
{
    public async override Task<HttpResponseMessage> ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)
    {
        var response = base.ExecuteAsync(controllerContext, cancellationToken);

        if (response.IsFaulted)
        {
            HttpResponseMessage errorResponse = new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest);

            if (response.Exception.InnerException is NotImplementedException)
            {
                errorResponse.Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(new { ErrorCode = System.Net.HttpStatusCode.BadRequest, Message = response.Exception.InnerExceptions }));
            }

            errorResponse.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            return errorResponse;
        }

        return await response;
    }
}

感谢您的支持!

首先,这是一个范式问题: 继承之上的组成

其次,异常过滤器是专门为处理异常而别无其他设计的(遵循“ 单一职责”原则 )。

覆盖ExecuteAsync以处理异常就像走更长,更复杂的路线。 您必须编写更多的代码,并且有更多的可能性破坏某些内容。 喜欢:

  • 您确定来自base.ExecuteAsync的任务始终在检查IsFaulted之前完成吗?
  • 您确定在通过过滤器处理异常时,框架没有做任何其他工作吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM