SpringBoot封装通用异常
1.添加依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0..RELEASE</version>
</dependency>
2.自定义异常类
/**
*自定义异常类
*/
public class CommonException extends RuntimeException {
private ExceptionEnum exceptionEunm;
public CommonException(ExceptionEnum exceptionEunm) {
this.exceptionEunm = exceptionEunm;
}
public ExceptionEnum getExceptionEunm() {
return exceptionEunm;
}
public void setExceptionEunm(ExceptionEnum exceptionEunm) {
this.exceptionEunm = exceptionEunm;
}
}
3.自定义异常类型的枚举类
**
* 自定义异常类型的枚举类
*/
public enum ExceptionEnum {
PRICE_CANNOT_NULL(400,"价格不能为空"),
;
private final Integer code;
private final String msg;
ExceptionEnum(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public Integer getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
4.自定义异常返回数据
/**
* 自定义异常返回数据
*/
public class ExceptionResult {
private Integer status;
private String message;
private Long timestamp;
public ExceptionResult(ExceptionEnum exceptionEnum){
this.status= exceptionEnum.getCode();
this.message=exceptionEnum.getMsg();
this.timestamp = System.currentTimeMillis();
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Long getTimestamp() {
return timestamp;
}
public void setTimestamp(Long timestamp) {
this.timestamp = timestamp;
}
@Override
public String toString() {
return "ExceptionResult{" +
"status=" + status +
", message='" + message + '\'' +
", timestamp=" + timestamp +
'}';
}
}
5.通用异常通知
**
* 通用异常通知
* @ControllerAdvice:默认会自动拦截所有的Controller
*/
@ControllerAdvice
public class CommonExceptionHandler {
@ExceptionHandler(CommonException.class)//拦截指定抛出的自定义CommonException异常
public ResponseEntity<ExceptionResult> handlerException(CommonException e){
return ResponseEntity.status(e.getExceptionEunm().getCode())
.body(new ExceptionResult(e.getExceptionEunm()));
}
}
6.实体类
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;
}
@Override
public String toString() {
return "Item{" +
"id=" + id +
", name='" + name + '\'' +
", price=" + price +
'}';
}
}
7.写一个ItemController类测试
@RestController
@RequestMapping("/item")
public class ItemController {
@Autowired
private ItemService itemService;
@PostMapping()
public ResponseEntity<Item> saveItem(Item item){
if (item.getPrice() == null){
throw new CommonException(ExceptionEnum.PRICE_CANNOT_NULL);
}
Item item1 = itemService.saveItem(item);
return ResponseEntity.status(HttpStatus.CREATED).body(item1);
}
}
8.测试结果
成功返回

自定义异常返回


浙公网安备 33010602011771号