gpt4 book ai didi

c# - 如果抛出异常,.Net Web API 偶尔会完全不返回任何响应

转载 作者:行者123 更新时间:2023-11-30 12:38:11 24 4
gpt4 key购买 nike

首先介绍一下背景。
我在 Visual Studio 2017 社区中使用 .Net Framework 4.6.1、Microsoft.AspNet.WebApi 5.2.4。

我的 ApiController 的实现端点会抛出预期的异常,例如,如果不满足某些要求。我添加了全局 ExceptionFilterAttribute 和 ExceptionHandler 来处理这些异常并返回正确的响应。Exceptions 是继承自 System.Exception 的类型。
这只是偶尔按预期工作。每秒或第三次或有时第五次(没有真实模式)请求 api 服务器根本不返回任何响应,例如例如 postman 说:“无法得到任何回应”。
为了对此进行测试,我使用了具有相同输入的相同端点。

为了更好地了解问题,我做了一些事情:
我向 Global.asax 添加了异常日志记录(以捕获第一次机会异常)
我订阅了 Global.asax Application_Error 事件
我查看了 IIS 日志

这些都没有让我更接近这个问题。异常被捕获并按预期记录在 Global.asax 中,但没有其他错误或异常可以为我的问题提供更多信息。

这是我的代码:
我简化了 ApiController 的功能并删除了业务逻辑。

[Route("test")]
[HttpGet]
public IHttpActionResult GetTest()
{
throw new ObjectAlreadyExistsException("test");
return ResponseFactory.CreateOkResponse(null);
}

public class ExceptionFilter : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
if (context.Exception is ObjectAlreadyExistsException)
{
context.Response = ResponseFactory.CreateErrorResponseMessage(context.Exception.Message, new Error("OBJECT_ALREADY_EXISTS_ERROR", context.Exception.Message));
}
else if (context.Exception is ObjectNotFoundException)
{
context.Response = ResponseFactory.CreateErrorResponseMessage(context.Exception.Message, new Error("OBJECT_NOT_FOUND_ERROR", context.Exception.Message));
}

base.OnException(context);
}
}

public class GlobalExceptionHandler : ExceptionHandler
{
private static readonly ILogger Log = new LoggerConfiguration()
.WriteTo.File(new CompactJsonFormatter(), Path.Combine(@Properties.Settings.Default.LOG_DIRECTORY, @"error.json"), rollOnFileSizeLimit: true, retainedFileCountLimit: 5, shared: true)
.Enrich.WithWebApiControllerName()
.Enrich.WithWebApiActionName()
.Enrich.WithWebApiRouteTemplate()
.Enrich.WithWebApiRouteData()
.Enrich.With(new AuthTokenEnricher())
.CreateLogger();

public override void Handle(ExceptionHandlerContext context)
{
if (context != null && context.Exception != null)
{
Log.Error("Unexpected Internal Server Error {Exception}", context.Exception);
}

context.Result = ResponseFactory.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unexpected Internal Server Error", new Error("INTERNAL_SERVER_ERROR", "This request failed because of an unexpected server error."));
}
}

public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{

//Exception filters
config.Filters.Add(new ExceptionFilter());
config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler());

// Web API routes
config.MapHttpAttributeRoutes();
}
}

public class ObjectAlreadyExistsException : Exception
{
public ObjectAlreadyExistsException(string message) : base(message)
{
}

public ObjectAlreadyExistsException(string message, Exception inner) : base(message, inner)
{
}
}

现在我采用了如下所示的解决方法:

[Route("test")]
[HttpGet]
public IHttpActionResult GetTest()
{
try
{
throw new ObjectAlreadyExistsException("test");
}
catch (Exception ex)
{
return CustomExceptionHandler.Handle(ex);
}
}

public class CustomExceptionHandler
{
private static readonly ILogger Log = new LoggerConfiguration()
.WriteTo.File(new CompactJsonFormatter(), Path.Combine(@Properties.Settings.Default.LOG_DIRECTORY, @"error.json"), rollOnFileSizeLimit: true, retainedFileCountLimit: 5, shared: true)
.Enrich.WithWebApiControllerName()
.Enrich.WithWebApiActionName()
.Enrich.WithWebApiRouteTemplate()
.Enrich.WithWebApiRouteData()
.Enrich.With(new AuthTokenEnricher())
.CreateLogger();

public static IHttpActionResult Handle(Exception ex)
{
IHttpActionResult result = null;

if (ex != null)
{
if (ex is ObjectAlreadyExistsException)
{
result = ResponseFactory.CreateErrorResponse(ex.Message, new Error("OBJECT_ALREADY_EXISTS_ERROR", ex.Message));
}
else if (ex is ObjectNotFoundException)
{
result = ResponseFactory.CreateErrorResponse(ex.Message, new Error("OBJECT_NOT_FOUND_ERROR", ex.Message));
}
}

if (result == null)
{
if (ex != null)
{
Log.Error("Unexpected Internal Server Error {Exception}", ex);
}

result = ResponseFactory.CreateErrorResponse(HttpStatusCode.InternalServerError, "Unexpected Internal Server Error", new Error("INTERNAL_SERVER_ERROR", "This request failed because of an unexpected server error."));
}

return result;
}
}

如果有任何关于如何调试它的想法或任何修复它的建议,我将不胜感激。

最佳答案

您能否尝试从 IHttpActionResult 继承并将其用作从您的 GlobalExceptionHandler 返回异常

 private class ErrorMessageResult : IHttpActionResult
{
private readonly HttpResponseMessage _httpResponseMessage;
private HttpRequestMessage _request;

public ErrorMessageResult(HttpRequestMessage request, HttpResponseMessage httpResponseMessage)
{
_request = request;
_httpResponseMessage = httpResponseMessage;
}

public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
return Task.FromResult(_httpResponseMessage);
}
}

然后这样调用它,

public override void Handle(ExceptionHandlerContext context)
{
var result = new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent("Internal Server Error Occurred"),
ReasonPhrase = "Exception"
};

context.Result = new ErrorMessageResult(context.Request, result);
}

来自 GlobalExceptionHandler : ExceptionHandler

关于c# - 如果抛出异常,.Net Web API 偶尔会完全不返回任何响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55015802/

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