throw new SellException() 抛错会返回给前端吗?
来源:6-11 买家订单-api_B
慕斯卡2560167
2019-06-30
postMan调用cerate接口的时候,传递了一个不存在的productId,按道理接口应该返回SellException的错误吧,如图:
{
"timestamp": "2019-06-30T12:35:48.528+0000",
"status": 500,
"error": "Internal Server Error",
"exception": "com.imooc.exception.SellException",
"message": "商品不存在",
"path": "/sell/buyer/order/create"
}
但是实际上返回的是如下信息:
{
"timestamp": "2019-06-30T12:35:48.528+0000",
"status": 500,
"error": "Internal Server Error",
"message": "Unable to find com.imooc.sell.dataobject.ProductInfo with id 124334; nested exception is javax.persistence.EntityNotFoundException: Unable to find com.imooc.sell.dataobject.ProductInfo with id 124334",
"path": "/sell/buyer/order/create"
}
下面是我的代码:
@Override
@Transactional
public OrderDTO create(OrderDTO orderDTO) {
BigDecimal orderAmount = new BigDecimal(0);
String orderId = KeyUtil.genUniqueKey();
//查询商品
for(OrderDetail orderDetail: orderDTO.getOrderDetailList()) {
ProductInfo productInfo = productService.findeOne(orderDetail.getProductId());
if(productInfo == null) {
throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
}
//计算总价
orderAmount = productInfo.getProductPrice()
.multiply(new BigDecimal(orderDetail.getProductQuantity()))
.add(orderAmount);
//订单详情入库
orderDetail.setDetailId(KeyUtil.genUniqueKey());
orderDetail.setOrderId(orderId);
BeanUtils.copyProperties(productInfo, orderDetail);
orderDetailRepository.save(orderDetail);
}
//orderMaster入库
OrderMaster orderMaster = new OrderMaster();
orderDTO.setOrderId(orderId);
BeanUtils.copyProperties(orderDTO, orderMaster);
orderMaster.setOrderAmount(orderAmount);
orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode());
orderMaster.setPayStatus(PayStatusEnum.WAIT.getCode());
orderMasterRepository.save(orderMaster);
//扣库存
List<CartDTO> cartDTOList = orderDTO.getOrderDetailList()
.stream()
.map(e -> new CartDTO(e.getProductId(), e.getProductQuantity())).collect(Collectors.toList());
productService.decreaceStock(cartDTOList);
return orderDTO;
}
写回答
1回答
-
抛错是会返回的前端的。
你的代码量代码里,应该是在 repository 层里面没有查询到 productInfo 而直接抛出了异常,没有返回 null。可以尝试这样:
public class ProductServiceImpl implements ProductService { @Autowired private ProductInfoRepository repository; @Override public ProductInfo findOne(String productId) { // 如果没有查询到就返回 null return repository.findById(productId).orElse(null); } ... }
这样在 service 层,就可以接收到 null 并抛出正确的异常了。
希望能够解决你的问题 : )
112019-06-30
相似问题