优化业务错误顶层响应
This commit is contained in:
@@ -22,6 +22,43 @@ bool isRobotCommand(const std::string &req_cmd)
|
||||
req_cmd == "Cmd_SelectCraftTree" ||
|
||||
req_cmd == "Cmd_AddOperationTree";
|
||||
}
|
||||
|
||||
// 从业务返回体推导顶层 API 是否成功,避免把业务错误包装成成功响应。
|
||||
bool isBusinessResultSuccess(const json &res_data)
|
||||
{
|
||||
if (!res_data.is_object())
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (res_data.contains("success") && res_data["success"].is_boolean())
|
||||
{
|
||||
return res_data["success"].get<bool>();
|
||||
}
|
||||
|
||||
return !res_data.contains("error");
|
||||
}
|
||||
|
||||
// 提取业务错误信息,用于同步顶层 msg 字段。
|
||||
std::string getBusinessResultMessage(const json &res_data, const std::string &fallback)
|
||||
{
|
||||
if (isBusinessResultSuccess(res_data))
|
||||
{
|
||||
return fallback;
|
||||
}
|
||||
|
||||
if (res_data.contains("message") && res_data["message"].is_string())
|
||||
{
|
||||
return res_data["message"].get<std::string>();
|
||||
}
|
||||
|
||||
if (res_data.contains("error") && res_data["error"].is_string())
|
||||
{
|
||||
return res_data["error"].get<std::string>();
|
||||
}
|
||||
|
||||
return fallback.empty() ? "Business command failed" : fallback;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
KinematicsWebAPI::KinematicsWebAPI()
|
||||
@@ -62,7 +99,10 @@ std::string KinematicsWebAPI::func(std::string sanitized_body)
|
||||
const json req_param = request_json.value("req_param", json::object());
|
||||
|
||||
json res_data = dispatchCommand(req_cmd, req_param);
|
||||
return utils::create_api_response(true, 0, msg, req_code, req_from, req_cmd, res_data).dump();
|
||||
const bool business_success = isBusinessResultSuccess(res_data);
|
||||
const int code = business_success ? 0 : 1000;
|
||||
const std::string response_msg = getBusinessResultMessage(res_data, msg);
|
||||
return utils::create_api_response(business_success, code, response_msg, req_code, req_from, req_cmd, res_data).dump();
|
||||
}
|
||||
catch (const std::exception &e)
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user