首页 > 解决方案 > API 响应 Http 状态码和自定义错误码映射

问题描述

如何存储http状态码和错误码的映射关系。给出一个基本概念,我正在处理的状态代码和错误代码类似于twitter 错误代码

现在的问题是,如果我对单个 http 状态代码有多个错误代码(在 twitter 的情况下,错误代码 3,44,215,323,324,325,407 映射到 http 状态代码 400),我如何将这些值存储在我的代码中。我可以使用 Dictionary<int, List<int>>还是有其他方法可以做到这一点?

我将在异常中设置错误代码。异常过滤器将解析错误代码并设置适当的 http 状态代码并返回 API 响应。

异常类

public class APIException : Exception
{
    public int ErrorCode { get; set; }


    public APIException(int errorCode, string message) : base(message)
    {
        ErrorCode = errorCode;
    }
}

异常过滤器代码片段

var apiException = actionExecutedContext.Exception as APIException;

int statusCode = GetHttpStatusCode(apiException.ErrorCode)

var response = new HttpResponseMessage((HttpStatusCode)(statusCode));

var apiResult = new APIResult(apiException.ErrorCode, apiException.Message);

response.Content = new ObjectContent<APIResult>(apiResult, new JsonMediaTypeFormatter(), "application/json");

actionExecutedContext.Response = response;

现在的问题是关于GetHttpStatusCode()函数的实现。目前我正在考虑使用Dictionary<int, List<int>>来存储映射。通过在值(错误代码)中搜索来获取密钥(httpStatusCode)。

我可以有一个平面字典,其中错误代码是关键,http 状态代码是值。但是,如果我必须查看针对特定状态代码的所有错误代码,该列表将变得巨大并且可读性将变得困难。

标签: c#apiexceptionhttp-status-codeserror-code

解决方案


坦率地说,那用一本平面字典

[...] 如果我必须查看针对特定状态代码的所有错误代码,列表将变得庞大且可读性将变得困难。

不是让代码过于复杂和性能降低的一个很好的借口。虽然 的可读性Dictionary<int, List<int>>可能会更好一点,但代码本身的可读性(应该是重要的代码)会受到影响。恕我直言,这是代码结构欠佳的症状。

使用平面字典,查找变得如此简单

int GetHttpStatus(int errorCode)
{
   return errorCodeMappings[errorCode]; 
}

而且由于一个键不能在字典中多次存在,因此无法多次添加错误代码。

(作为一个优点,与使用反向查找的解决方案相比,这非常快Dictionary<int, List<int>>,因为您可以使用散列。虽然这很可能不是瓶颈,但可以免费使用。)

如果将其包装在某个StatusCodeMapper类中,则可以将构造函数定义为

public ErrorCodeMapper(Dictionary<int, List<int>> reverseMappings)
{
    // Convert mappings to a more efficient format
    this.mappings = reverseMappings.SelectMany(entry => entry.Value.Select(errorCode => new { errorCode, status=entry.Key}))
                                   .ToDictionary(mapping => mapping.errorCode, mapping => mapping.status)
}

并保留您Dictionary<int, List<int>>的最高级别,但如果按预期使用,请使用更简洁和更快的查找和自动检查您获得的重复错误代码Dictionary。如果您只创建 的单个实例ErrorCodeMapper,那么“昂贵”的代码(好吧,虽然不是太贵,但不仅仅是哈希查找)将只运行一次。


推荐阅读