笔记:通用异常处理

通用异常处理

1. 场景预设

新增商品类,接受以下两个参数:

price 价格
name 名称

对数据进行校验:
价格不能为空

2.代码实现

实体类:
public class Item {
    private Integer id;
    private String name;
    private Long price;
 
    public Integer getId() {
        return id;
    }
 
    public void setId(Integer id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public Long getPrice() {
        return price;
    }
 
    public void setPrice(Long price) {
        this.price = price;
    }
}
service类

对商品进行保存,仅仅只是演示用。

@Service
public class ItemSevice {
    public Item saveTtem(Item item){
        //商品新增
        int id = new Random().nextInt(100);
        item.setId(id);
        return item;
    }
}
web类:

对价格进行判断,如果为空则抛出异常。

@RestController
@RequestMapping("item")
public class ItemController {
    @Autowired
    private ItemSevice itemSevice;
 
    @PostMapping
    public ResponseEntity<Item> saveItem(Item item){
        //校验价格
        if (item.getPrice() == null){
           // return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
            throw new LyException(ExceptionEnum.PRICE_CANNOT_BE_NULL);
        }
        return ResponseEntity.status(HttpStatus.CREATED).body(item);
    }
}
LyException类

继承RuntimeException,是一个自定义异常类。该类的成员,是一个枚举类。

@AllArgsConstructor
@Getter
public class LyException extends RuntimeException{
    private ExceptionEnum exceptionEnum;
}
枚举类
@AllArgsConstructor
@NoArgsConstructor
@Getter
public enum  ExceptionEnum {

    PRIVE_CANNOT_BE_NULL(400,"价格不能为空!")
    ;
    private int code;
    private String msg;
}
异常结果类

对返回的异常结果进行封装

@Data
public class ExceptionResult {

    private int status;
    private  String message;
    private Long timestamp;

    public ExceptionResult(ExceptionEnum em){
        this.status = em.getCode();
        this.message = em.getMsg();
        this.timestamp = System.currentTimeMillis();
    }

}
通用处理类

需要注意,该类如果要被使用生效。那么需要使该类在被扫描的包路径下。

@ControllerAdvice
public class CommonExceptionHandler {

    @ExceptionHandler(LyException.class)
    public ResponseEntity<ExceptionResult> handleException(LyException e){
        //return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
        return ResponseEntity.status(e.getExceptionEnum().getCode())
                .body(new ExceptionResult(e.getExceptionEnum()));

    }

}
参考:

https://blog.csdn.net/id5555/article/details/89346291

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值