gpt4 book ai didi

c# - 使用FilterAttributes的Web API异常处理

转载 作者:行者123 更新时间:2023-12-03 08:50:08 25 4
gpt4 key购买 nike

我有一个捕获错误并记录错误的过滤器,但是我希望它返回正确的 HttpStatusCode ,以便我的客户端应用程序可以显示不错的错误消息。
当前,在我的过滤器属性的重写的 OnException 方法中,我尝试通过将异常转换为 HttpException 来获取状态码。
看起来像这样:

public class LogExceptionFilterAttribute : ExceptionFilterAttribute
{

// Private properties
private readonly ILogProvider _logger;

/// <summary>
/// Our default constructor
/// </summary>
/// <param name="logger"></param>
public LogExceptionFilterAttribute(ILogProvider logger)
{
_logger = logger;
}

/// <summary>
/// Invoked when an exception has been thrown
/// </summary>
/// <param name="context">The context</param>
public override async void OnException(HttpActionExecutedContext context)
{

// Get our user
var requestContext = context.Request.GetRequestContext();
var user = requestContext.Principal.Identity;

// Create our response
var message = await _logger.ErrorAsync(context.Exception, user);
var content = new HttpResponseMessage
{
Content = new StringContent(message),
StatusCode = GetStatusCodeFromException(context)
};

// Assign our response to our context
context.Response = content;
}

/// <summary>
/// Gets a status code from an error
/// </summary>
/// <param name="context">The context</param>
/// <returns></returns>
private static HttpStatusCode GetStatusCodeFromException(HttpActionExecutedContext context)
{

// Cast the exception as an HttpException
var exception = context.Exception as HttpException;

// If we don't have an exception
if (exception != null)
{

// Return the HttpException code
return (HttpStatusCode)exception.GetHttpCode();
}

// Return Internal Server Error
return HttpStatusCode.InternalServerError;
}
}

我意识到大多数错误不能转换为 HttpExceptions ,因此返回的状态代码将始终为500。

要解决此问题,我想添加任何异常类型的检查并进行相应处理。
我决定最好的方法是创建一个如下的switch语句:
private static HttpStatusCode GetStatusCodeFromException(HttpActionExecutedContext context)
{

// Cast the exception as an HttpException
var exception = context.Exception as HttpException;

// If there is still an exception, return the code
if (exception != null)
return (HttpStatusCode)exception.GetHttpCode();

// Otherwise, work out what type of error we have
switch(context.Exception.GetType().ToString())
{
case "NullReferenceException":
return HttpStatusCode.BadRequest;
default:
return HttpStatusCode.InternalServerError;
}
}

但是现在我不确定这是否正确。
有人可以帮助我扩展此范围还是告诉我一种更好的方法?

最佳答案

与其在名称上比较类型,不如实际检查类型本身要安全得多:

if (context.Exception is NullReferenceException)
{
return HttpStatusCode.BadProgrammer;
}
else
{
return HttpStatusCode.InternalServerError;
}

关于c# - 使用FilterAttributes的Web API异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43228123/

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