代码演示问题:
鉴于这不是我的代码,我讨厌将其称为错误,但经过数小时的尝试后,它开始有这种感觉。
using System;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.ExceptionHandling;
namespace WebApplication3.Controllers
{
public class TestController : ApiController
{
public async Task<string> Get()
{
var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(1));
return await new TestThing().ExecuteAsync(cancellationTokenSource.Token);
}
}
public class MyErrorHandler : ExceptionHandler
{
public override Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)
{
throw new HttpResponseException(HttpStatusCode.InternalServerError);
}
}
public class TestThing
{
public async Task<string> ExecuteAsync(CancellationToken cancellationToken)
{
// Remove this to see the problem, I don't want to add these
// try/catch statements all over the codebase.
try
{
await Task.Delay(TimeSpan.FromMinutes(1), cancellationToken);
}
catch (Exception ex)
{
throw new Exception("Failure...");
}
return await Task.FromResult("Testing...");
}
}
}
最佳答案
鉴于缺乏建议或答案,我使用了自定义消息处理程序。
public class AsyncFixHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
try
{
return await base.SendAsync(request, cancellationToken);
}
catch (TaskCanceledException)
{
// TODO: Log the issue here
return new HttpResponseMessage(HttpStatusCode.InternalServerError);
}
}
}
这并不理想,但 try/catch 位于一处。我正在成功地使用它作为解决方案,直到出现更好的东西。
关于c# - Web API 2 - 全局异常处理程序不适用于 TaskCancellation,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32566071/