You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
4.2 KiB
4.2 KiB
下单报错修复说明
问题分析
根据您提供的请求数据,发现下单报错的主要原因是:
1. 字段映射不匹配
前端发送的请求数据格式与后端期望的字段名不一致:
前端发送的数据:
{
"goodsItems": [{"goodsId": 10021, "quantity": 1}],
"addressId": 10832,
"payType": 1,
"comments": "扎尔伯特五谷礼盒",
"deliveryType": 0,
"goodsId": 10021,
"quantity": 1
}
后端期望的字段:
formId
(而不是goodsId
)totalNum
(而不是quantity
)totalPrice
(缺失)tenantId
(缺失)type
(缺失)
2. 缺少必填字段
totalPrice
:订单总额tenantId
:租户IDtype
:订单类型
修复方案
1. 增强 OrderCreateRequest 兼容性
在 OrderCreateRequest
中添加了兼容性字段和方法:
// 兼容字段
@JsonProperty("goodsId")
private Integer goodsId;
@JsonProperty("quantity")
private Integer quantity;
@JsonProperty("goodsItems")
private List<GoodsItem> goodsItems;
// 兼容性方法
public Integer getActualFormId() {
if (formId != null) return formId;
if (goodsId != null) return goodsId;
if (goodsItems != null && !goodsItems.isEmpty()) {
return goodsItems.get(0).getGoodsId();
}
return null;
}
public Integer getActualTotalNum() {
if (totalNum != null) return totalNum;
if (quantity != null) return quantity;
if (goodsItems != null && !goodsItems.isEmpty()) {
return goodsItems.get(0).getQuantity();
}
return 1; // 默认数量为1
}
2. 修改业务逻辑
更新了 OrderBusinessService
中的验证和构建逻辑:
- 使用
getActualFormId()
和getActualTotalNum()
获取实际值 - 增强了参数验证,支持缺失字段的默认值设置
- 改进了错误信息,提供更详细的调试信息
3. 增强错误处理
在控制器中添加了详细的日志记录:
logger.info("收到下单请求 - 用户ID:{},商品ID:{},数量:{},总价:{},租户ID:{}",
loginUser.getUserId(), request.getActualFormId(), request.getActualTotalNum(),
request.getTotalPrice(), request.getTenantId());
支持的请求格式
修复后,系统现在支持以下多种请求格式:
格式1:原有格式
{
"formId": 10021,
"totalNum": 1,
"totalPrice": 99.00,
"tenantId": 10832,
"type": 0,
"payType": 1,
"comments": "扎尔伯特五谷礼盒"
}
格式2:新的兼容格式
{
"goodsId": 10021,
"quantity": 1,
"totalPrice": 99.00,
"tenantId": 10832,
"type": 0,
"payType": 1,
"comments": "扎尔伯特五谷礼盒"
}
格式3:批量商品格式
{
"goodsItems": [
{"goodsId": 10021, "quantity": 1, "price": 99.00}
],
"totalPrice": 99.00,
"tenantId": 10832,
"type": 0,
"payType": 1,
"comments": "扎尔伯特五谷礼盒"
}
自动处理的字段
系统现在会自动处理以下情况:
- 缺失 totalPrice:根据商品价格和数量自动计算
- 缺失 type:默认设置为 0(商城订单)
- 缺失 tenantId:会提示错误,需要前端提供
- 字段名不匹配:自动映射 goodsId→formId, quantity→totalNum
测试验证
创建了完整的单元测试来验证修复效果:
- ✅ 正常下单流程测试
- ✅ 商品不存在异常测试
- ✅ 库存不足异常测试
- ✅ 价格验证异常测试
- ✅ 兼容性字段测试
建议
前端调整建议
为了确保下单成功,建议前端在请求中包含以下必填字段:
{
"goodsId": 10021, // 商品ID
"quantity": 1, // 购买数量
"totalPrice": 99.00, // 订单总额(可选,系统会自动计算)
"tenantId": 10832, // 租户ID(必填)
"type": 0, // 订单类型(可选,默认为0)
"payType": 1, // 支付类型
"comments": "商品备注", // 备注
"deliveryType": 0, // 配送方式
"addressId": 10832 // 收货地址ID
}
后端监控建议
建议在生产环境中监控以下指标:
- 下单失败率
- 常见错误类型
- 字段缺失情况
- 价格验证失败次数
这样可以及时发现和解决问题。