枚舉異常封裝
@Getter
public enum ResultEnum {
PARAM_ERROR(1, "參數不正確"),
PRODUCT_NOT_EXIST(10, "商品不存在"),
PRODUCT_STOCK_ERROR(11, "商品庫存不正確"),
ORDER_NOT_EXIST(12, "訂單不存在"),
ORDERDETAIL_NOT_EXIST(13, "訂單詳情不存在"),
ORDER_STATUS_ERROR(14, "訂單狀態不正確"),
ORDER_UPDATE_FAIL(15, "訂單更新失敗"),
ORDER_DETAIL_EMPTY(16, "訂單詳情爲空"),
ORDER_PAY_STATUS_ERROR(17, "訂單支付狀態不正確"),
CART_EMPTY(18, "購物車爲空"),
ORDER_OWNER_ERROR(19, "該訂單不屬於當前用戶"),
;
//數字
private Integer code;
//內容
private String message;
ResultEnum(Integer code, String message) {
this.code = code;
this.message = message;
}
}
- 1.繼承運行時異常百度
- 2.構造方法裏面傳枚舉對象
- 3.第二個手動設置異常
public class SellException extends RuntimeException{
private Integer code;
public SellException(ResultEnum resultEnum) {
//把枚舉對象裏面內容傳到父類構造方法裏
super(resultEnum.getMessage());
this.code = resultEnum.getCode();
}
public SellException(Integer code, String message) {
super(message);
this.code = code;
}
}
例如判斷屬性是空拋出異常(商品不存在)
- 1.new繼承異常的對象,傳進去一個枚舉對象
ProductInfo productInfo = productService.findOne(orderDetail.getProductId());
if (productInfo == null) {
throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
}