Skip to content

refactor: fix typos and improve error messages #229

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 11, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions src/common/limiter_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,17 +34,17 @@ impl TryFrom<&str> for LimiterData {
let a: i32 = if let Some(e) = iter.next() {
e.parse()?
} else {
return Err(anyhow::anyhow!("limiter is unvalid"));
return Err(anyhow::anyhow!("limiter is invalid"));
};
let b: i32 = if let Some(e) = iter.next() {
e.parse()?
} else {
return Err(anyhow::anyhow!("limiter is unvalid"));
return Err(anyhow::anyhow!("limiter is invalid"));
};
let c: i64 = if let Some(e) = iter.next() {
e.parse()?
} else {
return Err(anyhow::anyhow!("limiter is unvalid"));
return Err(anyhow::anyhow!("limiter is invalid"));
Comment on lines +37 to +47
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

重复的错误消息 'limiter is invalid' 可以通过辅助函数简化

🟢 Minor | 🧹 Code Smells

📋 问题详情

在三个不同的变量解析处(a、b、c)重复使用相同的错误消息 'limiter is invalid',这会导致代码冗余。建议提取一个辅助函数来统一处理此类错误,提高代码可维护性。

💡 解决方案

提取辅助函数来减少重复代码:

fn get_required_value<T>(iter: &mut impl Iterator<Item = &str>, error_msg: &str) -> anyhow::Result<T>
where
    T: std::str::FromStr,
    <T as std::str::FromStr>::Err: std::error::Error + 'static,
{
    iter.next()
        .ok_or_else(|| anyhow::anyhow!(error_msg))
        .and_then(|e| e.parse().map_err(|e| anyhow::anyhow!(e)))
}

然后替换现有代码:

@@ -34,17 +34,8 @@
-        let a: i32 = if let Some(e) = iter.next() {
-            e.parse()?
-        } else {
-            return Err(anyhow::anyhow!("limiter is invalid"));
-        };
-        let b: i32 = ... // 同样结构
-        let c: i64 = ... // 同样结构
+        let a = get_required_value(&mut iter, "limiter is invalid")?;
+        let b = get_required_value(&mut iter, "limiter is invalid")?;
+        let c = get_required_value(&mut iter, "limiter is invalid")?;

您的反馈对我们很重要!(建议右键在新标签页中打开以下链接)

有用意见👍无用意见👎错误意见❌

};
Ok(Self::new(a, b, c))
}
Expand Down
4 changes: 2 additions & 2 deletions src/console/v2/naming_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ pub async fn add_instance(
if !namespace_privilege.check_permission(&instance.namespace_id) {
user_no_namespace_permission!(&instance.namespace_id);
}
if !instance.check_vaild() {
if !instance.check_valid() {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

错误响应使用 HTTP 200 状态码不恰当

🟠 Critical | 🐞 Bugs

📋 问题详情

当实例检查无效时,返回 HTTP 200 状态码(Ok)但携带错误消息,这与语义不符。建议使用 400 等错误状态码以准确反映错误场景。

💡 解决方案

调整 HTTP 状态码为 400:

@@ -241,7 +241,7 @@
-                HttpResponse::Ok().json(ApiResult::<()>::error(
+                HttpResponse::BadRequest().json(ApiResult::<()>::error(

您的反馈对我们很重要!(建议右键在新标签页中打开以下链接)

有用意见👍无用意见👎错误意见❌

HttpResponse::Ok().json(ApiResult::<()>::error(
ERROR_CODE_SYSTEM_ERROR.to_string(),
Some("instance check is invalid".to_string()),
Expand Down Expand Up @@ -274,7 +274,7 @@ pub async fn remove_instance(
if !namespace_privilege.check_permission(&instance.namespace_id) {
user_no_namespace_permission!(&instance.namespace_id);
}
if !instance.check_vaild() {
if !instance.check_valid() {
HttpResponse::Ok().json(ApiResult::<()>::error(
ERROR_CODE_SYSTEM_ERROR.to_string(),
Some("instance check is invalid".to_string()),
Expand Down
2 changes: 1 addition & 1 deletion src/grpc/handler/naming_batch_instance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ impl BatchInstanceRequestHandler {
} else if !service_name.is_empty() {
service_name.clone()
} else {
return Err(anyhow::format_err!("serivceName is unvaild!"));
return Err(anyhow::format_err!("serviceName is invalid!"));
};

let mut instance = Instance {
Expand Down
2 changes: 1 addition & 1 deletion src/grpc/handler/naming_instance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ impl InstanceRequestHandler {
} else if let Some(v) = request.service_name {
Arc::new(v)
} else {
return Err(anyhow::format_err!("serivceName is unvaild!"));
return Err(anyhow::format_err!("serviceName is invalid!"));
};
let now = now_millis_i64();
let mut instance = Instance {
Expand Down
2 changes: 1 addition & 1 deletion src/naming/api_model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ impl ServiceInfoParam {
pub(crate) fn build_service_info(self) -> anyhow::Result<ServiceDetailDto> {
if let Some(service_name) = self.service_name {
if service_name.is_empty() {
return Err(anyhow::anyhow!("service_name is vaild"));
return Err(anyhow::anyhow!("service_name is valid"));
}
let metadata = if let Some(metadata_str) = self.metadata {
match NamingUtils::parse_metadata(&metadata_str) {
Expand Down
8 changes: 4 additions & 4 deletions src/naming/cluster/node_manage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ use std::{
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NodeStatus {
Valid,
Unvalid,
Invalid,
}

impl Default for NodeStatus {
Expand Down Expand Up @@ -363,14 +363,14 @@ impl InnerNodeManage {
*/
if !node.is_local && node.status == NodeStatus::Valid && node.last_active_time < timeout
{
node.status = NodeStatus::Unvalid;
Self::client_unvalid_instance(naming_actor, node);
node.status = NodeStatus::Invalid;
Self::client_invalid_instance(naming_actor, node);
}
}
self.update_process_range();
}

fn client_unvalid_instance(
fn client_invalid_instance(
naming_actor: &Option<Addr<NamingActor>>,
node: &mut ClusterInnerNode,
) {
Expand Down
2 changes: 1 addition & 1 deletion src/naming/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -385,7 +385,7 @@ impl NamingActor {
from_sync: bool,
) -> UpdateInstanceType {
instance.init();
//assert!(instance.check_vaild());
//assert!(instance.check_valid());
self.create_empty_service(key);
//let is_from_from_cluster = instance.is_from_cluster();
let at_process_range = if let Some(range) = &self.current_range {
Expand Down
2 changes: 1 addition & 1 deletion src/naming/dal/service_actor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ create index if not exists tb_service_key_idx on tb_service(namespace_id,service
Ok(())
}
else{
Err(anyhow::anyhow!("update_service:unvaild service info"))
Err(anyhow::anyhow!("update_service:invalid service info"))
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

错误消息描述不够具体,建议增强可读性

🟢 Minor | 🧹 Code Smells

📋 问题详情

错误消息 'update_service:invalid service info' 过于模糊,建议增加具体上下文信息(如缺少必要字段)以帮助调试。

💡 解决方案

增强错误消息的描述性:

@@ -63,7 +63,7 @@
-            Err(anyhow::anyhow!("update_service:invalid service info"))
+            Err(anyhow::anyhow!("update_service: 无效的服务信息,缺少必要字段或格式错误"))

您的反馈对我们很重要!(建议右键在新标签页中打开以下链接)

有用意见👍无用意见👎错误意见❌

}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/naming/dal/service_do.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ impl ServiceDO {
s
}

pub fn check_vaild(&self) -> bool {
pub fn check_valid(&self) -> bool {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

方法 'check_valid' 缺少返回值,导致编译错误

🔴 Blocker | 🐞 Bugs

📋 问题详情

在方法 'check_valid' 中,当条件不满足时未返回布尔值,导致函数无法正确返回,引发编译错误。必须在 else 分支中返回 false 以确保所有执行路径都有返回值。

💡 解决方案

方法 'check_valid' 缺少返回值,导致编译错误。需要添加 else 分支返回 false:

@@ -40,6 +40,7 @@
         (self.namespace_id.as_ref(), self.service_name.as_ref(), self.group_name.as_ref()) {
         true
     } else {
+        false
     }

您的反馈对我们很重要!(建议右键在新标签页中打开以下链接)

有用意见👍无用意见👎错误意见❌

if let (Some(namespace_id),Some(service_name),Some(group_name)) =
(self.namespace_id.as_ref(),self.service_name.as_ref(),self.group_name.as_ref()) {
true
Expand Down
2 changes: 1 addition & 1 deletion src/naming/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ impl NamingUtils {
format!("{}@@{}", group_name, service_name)
}

pub fn split_group_and_serivce_name(grouped_name: &str) -> Option<(String, String)> {
pub fn split_group_and_service_name(grouped_name: &str) -> Option<(String, String)> {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

使用 'split_once()' 替代 'split().collect()' 提升代码简洁性和效率

🟢 Minor | 🧹 Code Smells

📋 问题详情

当前代码使用 'split("@@").collect::<Vec<_>>()' 来分割字符串,这可能产生不必要的中间 Vec。改用 'split_once()' 可以更高效地处理恰好两次分割的情况,同时代码更简洁。

💡 解决方案

使用 'split_once()' 简化代码:

@@ -37,8 +37,3 @@
-    let split = grouped_name.split("&&").collect::<Vec<_>>();
-    if split.is_empty() {
-        return None;
-    }
-    if split.len() != 2 {
-        return None;
-    }
-    Some((split[0].to_string(), split[1].to_string()))
+    grouped_name.split_once("&&").map(|(group, service)| (group.to_string(), service.to_string()))

您的反馈对我们很重要!(建议右键在新标签页中打开以下链接)

有用意见👍无用意见👎错误意见❌

let split = grouped_name.split("@@").collect::<Vec<_>>();
if split.is_empty() {
return None;
Expand Down
6 changes: 3 additions & 3 deletions src/naming/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ impl Instance {
}
}

pub fn check_vaild(&self) -> bool {
pub fn check_valid(&self) -> bool {
if self.id.is_empty()
&& self.port == 0
&& self.service_name.is_empty()
Expand Down Expand Up @@ -210,11 +210,11 @@ pub struct ServiceKey {
}

impl ServiceKey {
pub fn new(namespace_id: &str, group_name: &str, serivce_name: &str) -> Self {
pub fn new(namespace_id: &str, group_name: &str, service_name: &str) -> Self {
Self {
namespace_id: Arc::new(namespace_id.to_owned()),
group_name: Arc::new(group_name.to_owned()),
service_name: Arc::new(serivce_name.to_owned()),
service_name: Arc::new(service_name.to_owned()),
}
}

Expand Down
6 changes: 3 additions & 3 deletions src/openapi/naming/instance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ pub async fn update_instance(
let instance = param.convert_to_instance();
match instance {
Ok(instance) => {
if !instance.check_vaild() {
if !instance.check_valid() {
HttpResponse::InternalServerError().body("instance check is invalid")
} else {
match appdata
Expand All @@ -115,7 +115,7 @@ pub async fn del_instance(
let instance = param.convert_to_instance();
match instance {
Ok(instance) => {
if !instance.check_vaild() {
if !instance.check_valid() {
HttpResponse::InternalServerError().body("instance check is invalid")
} else {
match appdata.naming_route.delete_instance(instance).await {
Expand All @@ -140,7 +140,7 @@ pub async fn beat_instance(
let instance = param.convert_to_instance();
match instance {
Ok(instance) => {
if !instance.check_vaild() {
if !instance.check_valid() {
HttpResponse::InternalServerError().body("instance check is invalid")
} else {
let tag = InstanceUpdateTag {
Expand Down
14 changes: 7 additions & 7 deletions src/openapi/naming/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,12 +77,12 @@ impl InstanceWebParams {

let grouped_name = self.service_name.unwrap_or_default();
if let Some((group_name, service_name)) =
NamingUtils::split_group_and_serivce_name(&grouped_name)
NamingUtils::split_group_and_service_name(&grouped_name)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

硬编码的错误消息应使用常量管理

🟢 Minor | 🧹 Code Smells

📋 问题详情

在多个地方使用硬编码的错误消息 'serviceName is invalid!',这可能导致不一致和维护困难。建议将这些消息定义为常量以提高可维护性。

💡 解决方案

将硬编码的错误消息定义为常量:

const INVALID_SERVICE_NAME_MSG: &str = "serviceName is invalid!";

然后替换现有代码:

@@ -80,7 +80,7 @@
-        return Err("serviceName is invalid!".to_owned());
+        return Err(INVALID_SERVICE_NAME_MSG.to_owned());

您的反馈对我们很重要!(建议右键在新标签页中打开以下链接)

有用意见👍无用意见👎错误意见❌

{
instance.service_name = Arc::new(service_name);
instance.group_name = Arc::new(group_name);
} else {
return Err("serivceName is unvaild!".to_owned());
return Err("serviceName is invalid!".to_owned());
}
if let Some(group_name) = self.group_name {
if !group_name.is_empty() {
Expand Down Expand Up @@ -121,12 +121,12 @@ impl InstanceWebQueryListParams {
let mut group_name = "".to_owned();
let grouped_name = self.service_name.clone().unwrap_or_default();
if let Some((_group_name, _service_name)) =
NamingUtils::split_group_and_serivce_name(&grouped_name)
NamingUtils::split_group_and_service_name(&grouped_name)
{
service_name = _service_name;
group_name = _group_name;
} else {
return Err("serivceName is unvaild!".to_owned());
return Err("serviceName is invalid!".to_owned());
}
if let Some(_group_name) = self.group_name.as_ref() {
if !_group_name.is_empty() {
Expand Down Expand Up @@ -219,7 +219,7 @@ impl BeatRequest {
if service_name_option.is_none() {
let grouped_name = self.service_name.unwrap();
if let Some((group_name, service_name)) =
NamingUtils::split_group_and_serivce_name(&grouped_name)
NamingUtils::split_group_and_service_name(&grouped_name)
{
instance.service_name = Arc::new(service_name);
instance.group_name = Arc::new(group_name);
Expand Down Expand Up @@ -263,7 +263,7 @@ impl BeatRequest {
if service_name_option.is_none() {
if let Some(grouped_name) = self.service_name {
if let Some((group_name, service_name)) =
NamingUtils::split_group_and_serivce_name(&grouped_name)
NamingUtils::split_group_and_service_name(&grouped_name)
{
instance.service_name = Arc::new(service_name);
instance.group_name = Arc::new(group_name);
Expand Down Expand Up @@ -323,7 +323,7 @@ impl BeatInfo {
};
if let Some(grouped_name) = self.service_name.as_ref() {
if let Some((group_name, service_name)) =
NamingUtils::split_group_and_serivce_name(grouped_name)
NamingUtils::split_group_and_service_name(grouped_name)
{
instance.service_name = Arc::new(service_name);
instance.group_name = Arc::new(group_name);
Expand Down
2 changes: 1 addition & 1 deletion test_cluster.sh
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ set -o errexit
action=$1

usage() {
echo "cmd args unvalid"
echo "cmd args invalid"
echo "usage: $0 start | start_debug | restart | restart_debug | kill | clean | test_naming"
exit 2
}
Expand Down
Loading