任何人都可以使用示例客户端应用程序解释IExceptionHandler的工作流程
我在本示例中面临以下问题:
我无法在ExceptionContext
找到IsOutermostCatchBlock
如果发生exception,则此HandleAsync
方法正在执行两次。
( https://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 ExecuteAsync(CancellationToken cancellationToken) { HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.InternalServerError); response.Content = new StringContent(Content); response.RequestMessage = Request; return Task.FromResult(response); } } } }
CatchBlock.IsTopLevel
IsOutermostCatchBlock
不存在。 改为使用CatchBlock.IsTopLevel
:
public virtual bool ShouldHandle(ExceptionHandlerContext context) { return context.ExceptionContext.CatchBlock.IsTopLevel; }
NuDoq上的源: ExceptionHandlerContext和ExceptionContextCatchBlock
上述就是C#学习教程:任何人都可以使用示例客户端应用程序解释IExceptionHandler的工作流程分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1000397.html