Can Anyone Explain the work flow of IExceptionHandler with Sample Client Application

一个人想着一个人 提交于 2020-01-01 09:25:09

问题


I am facing below issues in this Sample:

I am not able to find IsOutermostCatchBlock in ExceptionContext

If Exception occurs, this HandleAsync method is executing twice.

(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:


CatchBlock.IsTopLevel

IsOutermostCatchBlock does not exists. Use CatchBlock.IsTopLevel instead:

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

Source on NuDoq: ExceptionHandlerContext and ExceptionContextCatchBlock



来源:https://stackoverflow.com/questions/22038800/can-anyone-explain-the-work-flow-of-iexceptionhandler-with-sample-client-applica

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