gpt4 book ai didi

c# - 谁能用示例客户端应用程序解释 IExceptionHandler 的工作流程

转载 作者:太空狗 更新时间:2023-10-29 18:08:16 24 4
gpt4 key购买 nike

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

我无法在 ExceptionContext 中找到 IsOutermostCatchBlock

如果发生异常,此 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);
}
}
}
}

最佳答案

CatchBlock.IsTopLevel

IsOutermostCatchBlock 不存在。使用 CatchBlock.IsTopLevel 代替:

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

NuDoq 上的来源:ExceptionHandlerContextExceptionContextCatchBlock

关于c# - 谁能用示例客户端应用程序解释 IExceptionHandler 的工作流程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22038800/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com