[英]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.