通用异常处理
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