springCloud 自定义抛出异常

定义异常枚举

package com.imooc.product.enums;

import lombok.Getter;

 
@Getter
public enum ResultEnum {

    PRODUCT_NOT_EXIST(1, "商品不存在"),
    PRODUCT_STOCK_ERROR(2, "库存有误"),
    ;

    private Integer code;

    private String message;

    ResultEnum(Integer code, String message) {
        this.code = code;
        this.message = message;
    }
}

自定义Exception

package com.imooc.product.exception;

import com.imooc.product.enums.ResultEnum;


public class ProductException extends RuntimeException {

    private Integer code;

    public ProductException(Integer code, String message) {
        super(message);
        this.code = code;
    }

    public ProductException(ResultEnum resultEnum) {
        super(resultEnum.getMessage());
        this.code = resultEnum.getCode();
    }
}

调用

 //判断商品是否存在
            if (!productInfoOptional.isPresent()){
                throw new ProductException(ResultEnum.PRODUCT_NOT_EXIST);
            }
发布了283 篇原创文章 · 获赞 11 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/liuming690452074/article/details/104522060