use std::collections::HashMap;
use std::sync::OnceLock;
use parking_lot::RwLock;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(i32)]
pub enum ErrorCode {
Ok = 200,
BadRequest = 400,
Unauthorized = 401,
Forbidden = 403,
NotFound = 404,
MethodNotAllowed = 405,
Conflict = 409,
UnprocessableEntity = 422,
TooManyRequests = 429,
Internal = 500,
ServiceUnavailable = 503,
}
impl ErrorCode {
pub fn default_message(self) -> &'static str {
match self {
ErrorCode::Ok => "ok",
ErrorCode::BadRequest => "请求参数错误",
ErrorCode::Unauthorized => "未授权,请先登录",
ErrorCode::Forbidden => "权限不足",
ErrorCode::NotFound => "资源不存在",
ErrorCode::MethodNotAllowed => "请求方法不允许",
ErrorCode::Conflict => "资源冲突",
ErrorCode::UnprocessableEntity => "请求语义错误",
ErrorCode::TooManyRequests => "请求过于频繁",
ErrorCode::Internal => "服务器内部错误",
ErrorCode::ServiceUnavailable => "服务暂时不可用",
}
}
pub fn http_status(self) -> u16 {
self as u16
}
pub fn from_i32(code: i32) -> Option<Self> {
match code {
200 => Some(ErrorCode::Ok),
400 => Some(ErrorCode::BadRequest),
401 => Some(ErrorCode::Unauthorized),
403 => Some(ErrorCode::Forbidden),
404 => Some(ErrorCode::NotFound),
405 => Some(ErrorCode::MethodNotAllowed),
409 => Some(ErrorCode::Conflict),
422 => Some(ErrorCode::UnprocessableEntity),
429 => Some(ErrorCode::TooManyRequests),
500 => Some(ErrorCode::Internal),
503 => Some(ErrorCode::ServiceUnavailable),
_ => None,
}
}
const ALL: [ErrorCode; 11] = [
ErrorCode::Ok,
ErrorCode::BadRequest,
ErrorCode::Unauthorized,
ErrorCode::Forbidden,
ErrorCode::NotFound,
ErrorCode::MethodNotAllowed,
ErrorCode::Conflict,
ErrorCode::UnprocessableEntity,
ErrorCode::TooManyRequests,
ErrorCode::Internal,
ErrorCode::ServiceUnavailable,
];
}
impl From<ErrorCode> for i32 {
fn from(code: ErrorCode) -> i32 {
code as i32
}
}
impl std::fmt::Display for ErrorCode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", *self as i32)
}
}
static REGISTRY: OnceLock<RwLock<HashMap<i32, String>>> = OnceLock::new();
fn registry() -> &'static RwLock<HashMap<i32, String>> {
REGISTRY.get_or_init(|| {
let mut map = HashMap::with_capacity(ErrorCode::ALL.len());
for code in ErrorCode::ALL {
map.insert(code as i32, code.default_message().to_string());
}
RwLock::new(map)
})
}
pub fn register(code: impl Into<i32>, msg: impl Into<String>) {
registry().write().insert(code.into(), msg.into());
}
pub fn register_all(entries: impl IntoIterator<Item = (impl Into<i32>, impl Into<String>)>) {
let mut reg = registry().write();
for (code, msg) in entries {
reg.insert(code.into(), msg.into());
}
}
pub fn error_message(code: i32) -> String {
let reg = registry().read();
if let Some(msg) = reg.get(&code) {
return msg.clone();
}
ErrorCode::from_i32(code)
.map(|e| e.default_message().to_string())
.unwrap_or_else(|| "未知错误".to_string())
}
pub fn error_message_of(code: ErrorCode) -> String {
error_message(code as i32)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn error_code_roundtrip_from_i32() {
for code in ErrorCode::ALL {
let n = code as i32;
assert_eq!(ErrorCode::from_i32(n), Some(code));
assert_eq!(code.http_status(), n as u16);
assert_eq!(i32::from(code), n);
assert_eq!(code.to_string(), n.to_string());
}
assert_eq!(ErrorCode::from_i32(418), None);
}
#[test]
fn default_messages_are_registered() {
for code in ErrorCode::ALL {
assert_eq!(error_message_of(code), code.default_message());
}
}
#[test]
fn register_custom_code() {
register(19_001, "用户名已存在");
assert_eq!(error_message(19_001), "用户名已存在");
assert_eq!(error_message(19_002), "未知错误");
}
#[test]
fn register_all_batch() {
register_all([
(19_101, "A"),
(19_102, "B"),
(ErrorCode::Ok as i32 + 19_000, "C"),
]);
assert_eq!(error_message(19_101), "A");
assert_eq!(error_message(19_102), "B");
assert_eq!(error_message(19_200), "C");
}
#[test]
fn unknown_code_falls_back_to_unknown() {
assert_eq!(error_message(-1), "未知错误");
assert_eq!(error_message(999_999), "未知错误");
}
}