use axum::{
response::{IntoResponse, Response},
http::StatusCode,
Json,
};
use serde_json::json;
// Custom error type for handlers
#[derive(Debug)]
enum AppError {
Wacht(wacht::Error),
Validation(String),
NotFound(String),
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let (status, message) = match self {
AppError::Wacht(Error::Api { status, message, .. }) => {
(status, message)
}
AppError::Wacht(_) => {
(StatusCode::INTERNAL_SERVER_ERROR, "Internal error".to_string())
}
AppError::Validation(msg) => {
(StatusCode::BAD_REQUEST, msg)
}
AppError::NotFound(msg) => {
(StatusCode::NOT_FOUND, msg)
}
};
(status, Json(json!({ "error": message }))).into_response()
}
}
// Usage in handler
async fn get_user_handler(
Path(user_id): Path<String>
) -> Result<Json<User>, AppError> {
let user = UsersApi::users_user_id_get(&user_id)
.await
.map_err(AppError::Wacht)?;
Ok(Json(user))
}