Skip to content

Commit 501aeb1

Browse files
committed
feat: 增强错误处理,添加更多错误类型和验证消息,优化用户创建和删除逻辑
1 parent ae1c52e commit 501aeb1

File tree

2 files changed

+58
-15
lines changed

2 files changed

+58
-15
lines changed

src/errors.rs

Lines changed: 41 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,33 @@ use sea_orm::DbErr;
44
use serde::Serialize;
55
use std::fmt;
66

7+
/// 应用程序的统一错误类型
78
#[derive(Debug)]
89
pub enum AppError {
10+
/// 数据库相关错误
911
DbError(DbErr),
12+
/// JWT 相关错误
1013
JwtError(JwtError),
14+
/// 校验失败错误,包含错误信息
1115
ValidationError(String),
16+
/// 资源未找到错误,包含错误信息
1217
NotFound(String),
18+
/// 未授权访问错误,包含错误信息
1319
Unauthorized(String),
20+
/// 内部服务器错误,包含错误信息
1421
InternalError(String),
22+
/// 解析错误,包含错误信息
23+
ParseError(String),
24+
/// 冲突错误,包含错误信息
25+
Conflict(String),
26+
/// 禁止访问错误,包含错误信息
27+
Forbidden(String),
28+
/// 请求超时错误,包含错误信息
29+
Timeout(String),
30+
/// 错误请求,包含错误信息
31+
BadRequest(String),
32+
/// 服务不可用,包含错误信息
33+
ServiceUnavailable(String),
1534
}
1635

1736
#[derive(Serialize)]
@@ -23,12 +42,18 @@ struct ErrorResponse {
2342
impl fmt::Display for AppError {
2443
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2544
match self {
26-
AppError::DbError(e) => write!(f, "Database error: {}", e),
27-
AppError::JwtError(e) => write!(f, "Token error: {}", e),
45+
AppError::DbError(e) => write!(f, "{e}"),
46+
AppError::JwtError(e) => write!(f, "{e}"),
2847
AppError::ValidationError(m)
2948
| AppError::NotFound(m)
3049
| AppError::Unauthorized(m)
31-
| AppError::InternalError(m) => write!(f, "{}", m),
50+
| AppError::InternalError(m)
51+
| AppError::ParseError(m)
52+
| AppError::Conflict(m)
53+
| AppError::Forbidden(m)
54+
| AppError::Timeout(m)
55+
| AppError::BadRequest(m)
56+
| AppError::ServiceUnavailable(m) => write!(f, "{m}"),
3257
}
3358
}
3459
}
@@ -37,9 +62,15 @@ impl ResponseError for AppError {
3762
fn status_code(&self) -> StatusCode {
3863
match self {
3964
AppError::DbError(_) | AppError::InternalError(_) => StatusCode::INTERNAL_SERVER_ERROR,
40-
AppError::ValidationError(_) => StatusCode::BAD_REQUEST,
65+
AppError::ValidationError(_) | AppError::ParseError(_) | AppError::BadRequest(_) => {
66+
StatusCode::BAD_REQUEST
67+
}
4168
AppError::NotFound(_) => StatusCode::NOT_FOUND,
4269
AppError::Unauthorized(_) | AppError::JwtError(_) => StatusCode::UNAUTHORIZED,
70+
AppError::Conflict(_) => StatusCode::CONFLICT,
71+
AppError::Forbidden(_) => StatusCode::FORBIDDEN,
72+
AppError::Timeout(_) => StatusCode::REQUEST_TIMEOUT,
73+
AppError::ServiceUnavailable(_) => StatusCode::SERVICE_UNAVAILABLE,
4374
}
4475
}
4576
fn error_response(&self) -> HttpResponse {
@@ -50,7 +81,6 @@ impl ResponseError for AppError {
5081
}
5182
}
5283

53-
// 自动从 sea_orm::DbErr & jsonwebtoken::Error 转换
5484
impl From<DbErr> for AppError {
5585
fn from(e: DbErr) -> Self {
5686
AppError::DbError(e)
@@ -61,3 +91,9 @@ impl From<JwtError> for AppError {
6191
AppError::JwtError(e)
6292
}
6393
}
94+
95+
impl From<std::num::ParseIntError> for AppError {
96+
fn from(e: std::num::ParseIntError) -> Self {
97+
AppError::ParseError(format!("{e}"))
98+
}
99+
}

src/handlers/users.rs

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ use sea_orm::{
88
ActiveModelTrait, ActiveValue::NotSet, ColumnTrait, DeleteResult, EntityTrait, QueryFilter, Set,
99
};
1010
use serde::{Deserialize, Serialize};
11+
use validator::Validate;
1112

1213
#[derive(Deserialize, Serialize, Debug)]
1314
struct Info {
@@ -45,7 +46,7 @@ pub async fn get_query_users(
4546
#[derive(Deserialize, Serialize, Debug, Validate)]
4647
struct CreateUser {
4748
name: String,
48-
#[validate(email)]
49+
#[validate(email(message = "无效的邮箱地址"))]
4950
email: String,
5051
pass_word: String,
5152
}
@@ -55,11 +56,15 @@ pub async fn create_user(
5556
app_data: web::Data<AppState>,
5657
) -> Result<HttpResponse, AppError> {
5758
println!("{:#?}", params);
59+
// 参数验证
60+
if let Err(e) = params.validate() {
61+
return Err(AppError::ValidationError(format!("{e}")));
62+
}
5863

5964
let argon2_config = argon2::Config::default();
6065
let hashed_password =
6166
argon2::hash_encoded(params.pass_word.as_bytes(), ARGON2_SALT, &argon2_config)
62-
.map_err(|e| AppError::InternalError(format!("Password hashing error: {}", e)))?;
67+
.map_err(|e| AppError::InternalError(format!("{e}")))?;
6368

6469
// 使用 sea-orm 创建用户
6570
let user = users::ActiveModel {
@@ -84,10 +89,13 @@ pub async fn create_user(
8489

8590
#[delete("/users/delete/{id}")]
8691
pub async fn delete_user(
87-
id: web::Path<i64>,
92+
id: web::Path<String>,
8893
app_data: web::Data<AppState>,
8994
) -> Result<HttpResponse, AppError> {
90-
let user_id = id.into_inner();
95+
let id_str = id.into_inner();
96+
let user_id: i64 = id_str
97+
.parse()
98+
.map_err(|_| AppError::ParseError(format!("无法解析用户ID: {id_str}")))?;
9199
println!("删除用户 ID: {}", user_id);
92100

93101
// 先删除该用户下的所有设备
@@ -99,12 +107,11 @@ pub async fn delete_user(
99107

100108
// 使用 sea-orm 删除用户
101109
let model = users::Entity::find_by_id(user_id).one(&app_data.db).await?;
102-
let user: users::ActiveModel = model
103-
.ok_or(AppError::NotFound(format!(
104-
"User with id {} not found",
105-
user_id
106-
)))?
107-
.into();
110+
if model.is_none() {
111+
// 统一返回 AppError::NotFound,保证响应格式一致
112+
return Err(AppError::NotFound(format!("用户ID {user_id} 不存在")));
113+
}
114+
let user: users::ActiveModel = model.unwrap().into();
108115

109116
let delete_result = user.delete(&app_data.db).await?;
110117
println!("删除结果: {:?}", delete_result);

0 commit comments

Comments
 (0)