.Net Core API如何处理HTTP异常



我通过一些示例创建了ErrorController,它正在处理Exception。目前我有这个:

[Route("[controller]")]
[ApiController]
[Authorize]
[ApiExplorerSettings(IgnoreApi = true)]
public class ErrorController : ControllerBase
{
public IActionResult ServerError()
{
var feature = HttpContext.Features.Get<IExceptionHandlerFeature>();
ErrorResponse response;

if (feature != null && feature.Error.GetType() == typeof(HttpResponseException))
{
response = new ErrorResponse
{
Error = "Error during processing request",
Message = feature.Error.Message
};
HttpContext.Response.StatusCode = ((HttpResponseException) feature.Error).HttpCode;
}
else
{
response = new ErrorResponse
{
Error = "Unexpected Server Error",
Message = feature?.Error.Message
};
}

return Content(JsonSerializer.Serialize(response), "application/json");
}    
}

因此,每当我在控制器HttpResponseException中抛出我的方法时,它都会读取它,并用相应的代码创建响应。但通过此操作,将记录HttpResponseException,这不是所需的行为。

我已经找到了Request.CreateResponse()的解决方案,但该方法并不存在,但当我自己复制该方法时,它不是所需的行为(因为Swashbuck/Swagger UI-返回类型不是模型对象,而是HttpResponseMessage(。

还发现了一些关于ExceptionFilterAttribute的东西,我在其中生成了以下代码:

public class HttpExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
if (!(context.Exception is HttpResponseException)) return;

var exception = (HttpResponseException) context.Exception;
context.Result = new ObjectResult(""){StatusCode = exception.HttpCode};
}
}

但不知道在哪里进行全球注册(基于本文(。

那么,如何正确管理返回的所需对象或代码中的一些错误,使其不会被记录为警告呢?

过滤器通过AddMVC或AddControllersWithViews选项在Startup.cs中全局注册。

另一种全局处理异常的方法是使用异常处理中间件,它也可以捕获意外异常(这是我的首选方法(。

最新更新