1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
| #include <flat_map>
#include <string_view>
#include <algorithm>
enum class ErrorCode : uint16_t {
Ok = 0,
NotFound = 404,
Forbidden = 403,
Internal = 500,
Timeout = 504
};
// 编译期初始化的 flat_map(小数据集)
// 枚举值 → 字符串名
const std::flat_map<ErrorCode, std::string_view> errorNames = {
{ErrorCode::Ok, "OK"},
{ErrorCode::NotFound, "Not Found"},
{ErrorCode::Forbidden, "Forbidden"},
{ErrorCode::Internal, "Internal Server Error"},
{ErrorCode::Timeout, "Gateway Timeout"}
};
// 字符串 → 枚举值(反向映射)
const std::flat_map<std::string_view, ErrorCode> errorByName = {
{"Forbidden", ErrorCode::Forbidden},
{"Gateway Timeout", ErrorCode::Timeout},
{"Internal Server Error", ErrorCode::Internal},
{"Not Found", ErrorCode::NotFound},
{"OK", ErrorCode::Ok}
};
std::string_view getErrorName(ErrorCode code)
{
auto it = errorNames.find(code);
return it != errorNames.end() ? it->second : "Unknown";
}
ErrorCode parseErrorCode(std::string_view name)
{
auto it = errorByName.find(name);
return it != errorByName.end() ? it->second : ErrorCode::Internal;
}
|