繁体   English   中英

API 响应 Http 状态码和自定义错误码映射

[英]API Response Http Status Code and Custom Error Codes Mapping

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

Now the question is if I have multiple error codes for a single http status code (in case of twitter the error codes 3,44,215,323,324,325,407 are mappedd to the http status code 400), how do I store this values in my code. 我是使用Dictionary<int, List<int>>还是有其他方法可以做到这一点?

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

异常 Class

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() function 的实现。 目前我正在考虑使用Dictionary<int, List<int>>来存储映射。 通过在值(错误代码)中搜索来获取密钥(httpStatusCode)。

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

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

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

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

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

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

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

(另外,与使用Dictionary<int, List<int>>和反向查找的解决方案相比,这是超快的,因为您可以使用散列。虽然这很可能不是瓶颈,但这很好免费拥有。)

如果您将其包装在一些StatusCodeMapper class 中,您可以将构造函数定义为

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实例,“昂贵”的代码(好吧,虽然不是太贵,但比 hash 查找更多)将只运行一次。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM