c# - 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 状态代码是值。但是,如果我必须查看针对特定状态代码的所有错误代码,该列表将变得巨大并且可读性将变得困难。
解决方案
坦率地说,那用一本平面字典
[...] 如果我必须查看针对特定状态代码的所有错误代码,列表将变得庞大且可读性将变得困难。
不是让代码过于复杂和性能降低的一个很好的借口。虽然 的可读性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
,那么“昂贵”的代码(好吧,虽然不是太贵,但不仅仅是哈希查找)将只运行一次。
推荐阅读
- c - 我在输出的末尾得到了 printf 行内的所有行
- flutter - Flutter - 找不到资产的文件或变体:lib/assets/images
- python - PyTorch 输入和隐藏张量不在同一设备上
- javascript - Firestore NoSql 数据库结构(作为 n 叉树)
- java - 带数据库的快速排名系统
- sparql - 在 where 子句中使用嵌套三元组时,SPARQL* DELETE/INSERT 返回错误
- kotlin - 为什么 Flux.flatMap() 不等待内部发布者完成?
- mysql - 许多大表中的mysql使一列相同
- qt - 菜单的 QML 动画
- php - 如何从 Firebase 数据库读取数据到 Laravel