You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让系统拒绝创建含不存在商品的订单并返回错误?

解决订单系统无效商品处理问题

核心思路

在创建订单流程中,提前校验传入的productName对应的商品是否存在,若不存在则直接中断流程并返回错误响应,杜绝无效订单生成。

具体修改步骤

1. 在业务层添加商品存在性校验

修改OrderService的订单创建方法,先通过商品名称查询商品信息,不存在则抛出业务异常:

@Service
public class OrderService {
    @Autowired
    private ProductService productService;
    @Autowired
    private OrderRepository orderRepository;

    public Order createOrder(OrderDTO orderDTO) {
        // 第一步:校验商品是否存在
        Product product = productService.getProductByName(orderDTO.getProductName());
        if (product == null) {
            throw new RuntimeException("商品" + orderDTO.getProductName() + "不存在,无法创建订单");
        }

        // 第二步:构建有效订单对象
        Order order = new Order();
        order.setProductId(product.getId());
        order.setAmount(product.getPrice() * orderDTO.getQuantity());
        // 其他订单字段赋值逻辑...

        // 第三步:保存并返回订单
        return orderRepository.save(order);
    }
}

2. 自定义业务异常(可选但推荐)

创建专属异常类,让错误更具辨识度:

public class ProductNotFoundException extends RuntimeException {
    public ProductNotFoundException(String message) {
        super(message);
    }
}

替换OrderService中的异常抛出语句:

throw new ProductNotFoundException("商品" + orderDTO.getProductName() + "不存在,无法创建订单");

3. 在控制层处理异常并返回错误响应

通过全局异常处理器或控制器内部捕获异常,返回标准化错误:

方式一:全局异常处理器

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(ProductNotFoundException.class)
    public ResponseEntity<String> handleProductNotFound(ProductNotFoundException e) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
    }
}

方式二:控制器内部捕获

@RestController
@RequestMapping("/orders")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @PostMapping
    public ResponseEntity<?> createOrder(@RequestBody OrderDTO orderDTO) {
        try {
            Order order = orderService.createOrder(orderDTO);
            return ResponseEntity.ok(order);
        } catch (ProductNotFoundException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
}

4. 补充参数合法性校验

在OrderDTO中添加注解,提前拦截空商品名称等非法请求:

public class OrderDTO {
    @NotBlank(message = "商品名称不能为空")
    private String productName;

    @Min(value = 1, message = "购买数量不能小于1")
    private Integer quantity;

    // getter、setter方法...
}

同时在控制器方法上添加@Valid启用校验:

@PostMapping
public ResponseEntity<?> createOrder(@Valid @RequestBody OrderDTO orderDTO) {
    // ...
}

关键注意点

  • 校验逻辑必须放在业务层,避免无效数据进入持久层
  • 异常处理要统一格式,保证前端能清晰识别错误原因
  • 配合参数校验,提前拦截明显非法的请求,减少无效业务逻辑执行

内容的提问来源于stack exchange,提问作者Dadinho2000

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 02:35:16