fix(server): better error responses when creating users

This commit is contained in:
perf3ct 2025-06-24 17:33:59 +00:00
parent 3f3654c3cb
commit 363bc2b9ef
2 changed files with 39 additions and 14 deletions

View File

@ -1,7 +1,7 @@
use axum::{
extract::State,
http::StatusCode,
response::Json,
response::{IntoResponse, Json, Response},
routing::{get, post},
Router,
};
@ -33,14 +33,35 @@ pub fn router() -> Router<Arc<AppState>> {
async fn register(
State(state): State<Arc<AppState>>,
Json(user_data): Json<CreateUser>,
) -> Result<Json<UserResponse>, StatusCode> {
let user = state
.db
.create_user(user_data)
.await
.map_err(|_| StatusCode::BAD_REQUEST)?;
Ok(Json(user.into()))
) -> Response {
match state.db.create_user(user_data).await {
Ok(user) => {
let user_response: UserResponse = user.into();
(StatusCode::OK, Json(user_response)).into_response()
}
Err(e) => {
tracing::error!("User registration failed: {}", e);
// Check for specific database constraint violations
let error_message = if e.to_string().contains("users_username_key") {
"Username already exists"
} else if e.to_string().contains("users_email_key") {
"Email already exists"
} else if e.to_string().contains("duplicate key") {
"User with this username or email already exists"
} else {
"Registration failed due to invalid data"
};
(
StatusCode::BAD_REQUEST,
Json(serde_json::json!({
"error": error_message,
"details": e.to_string()
}))
).into_response()
}
}
}
#[utoipa::path(

View File

@ -84,8 +84,9 @@ impl AdminTestClient {
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_millis();
let username = format!("user_test_{}", timestamp);
let email = format!("user_test_{}@example.com", timestamp);
let random_suffix = uuid::Uuid::new_v4().simple().to_string()[..8].to_string();
let username = format!("user_test_{}_{}", timestamp, random_suffix);
let email = format!("user_test_{}@example.com", random_suffix);
let password = "userpassword123";
// Register regular user
@ -103,7 +104,9 @@ impl AdminTestClient {
.await?;
if !register_response.status().is_success() {
return Err(format!("User registration failed: {}", register_response.text().await?).into());
let status = register_response.status();
let error_text = register_response.text().await.unwrap_or_else(|_| "Unknown error".to_string());
return Err(format!("User registration failed with status {}: {}", status, error_text).into());
}
// Login user
@ -478,8 +481,9 @@ async fn test_admin_user_management_without_roles() {
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_millis();
let username = format!("role_test_user_{}", timestamp);
let email = format!("roletest_{}@example.com", timestamp);
let random_suffix = uuid::Uuid::new_v4().simple().to_string()[..8].to_string();
let username = format!("role_test_user_{}_{}", timestamp, random_suffix);
let email = format!("roletest_{}@example.com", random_suffix);
let regular_user = client.create_user(&username, &email, UserRole::User, true).await
.expect("Failed to create regular user");