任何人都可以使用示例客户端应用程序解释IExceptionHandler的工作流程

时间:2014-02-26 10:38:31

标签: c# asp.net-web-api

我在本示例中面临以下问题:

我无法在IsOutermostCatchBlock

中找到ExceptionContext

如果发生异常,则此HandleAsync方法正在执行两次。

http://www.asp.net/web-api/overview/web-api-routing-and-actions/web-api-global-error-handling

public class CustomExceptionHandler : IExceptionHandler
{
    public virtual Task HandleAsync(ExceptionHandlerContext context,
                                        CancellationToken cancellationToken)
    {
        if (!ShouldHandle(context))
        {
            return Task.FromResult(0);
        }

            return HandleAsyncCore(context, cancellationToken);
        }

        public virtual Task HandleAsyncCore(ExceptionHandlerContext context,
                                            CancellationToken cancellationToken)
        {
            HandleCore(context);
            return Task.FromResult(0);
        }

        public virtual void HandleCore(ExceptionHandlerContext context)
        {
        }

        public virtual bool ShouldHandle(ExceptionHandlerContext context)
        {    
             return context.ExceptionContext.IsOutermostCatchBlock;
        }

    }

    public class OopsExceptionHandler : CustomExceptionHandler
    {
        public override void HandleCore(ExceptionHandlerContext context)
        {
            context.Result = new TextPlainErrorResult
            {
                Request = context.ExceptionContext.Request,
                Content = "Oops! Sorry! Something went wrong." +
                          "Please contact support@contoso.com so we can try to fix it."
            };
        }

        private class TextPlainErrorResult : IHttpActionResult
        {
            public HttpRequestMessage Request { get; set; }
            public string Content { get; set; }

            public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
            {
                HttpResponseMessage response =
                                 new HttpResponseMessage(HttpStatusCode.InternalServerError);
                response.Content = new StringContent(Content);
                response.RequestMessage = Request;
                return Task.FromResult(response);
            }
        }
    }
}

1 个答案:

答案 0 :(得分:19)

CatchBlock.IsTopLevel

IsOutermostCatchBlock不存在。 请改用 CatchBlock.IsTopLevel

public virtual bool ShouldHandle(ExceptionHandlerContext context)
{
  return context.ExceptionContext.CatchBlock.IsTopLevel;
}

NuDoq上的来源:ExceptionHandlerContextExceptionContextCatchBlock