处理异常的核心思想:逐层上抛,统一处理。
在java的lang包里面有一个类是Throwable,他的子类中有Error和Exception。
其中Error是jdk运行代码的时候发生的错误我们人为是不可以控制的。
所以关于异常我们主要研究的还是Exception。
其中异常又分为运行时期异常(RuntimeException)
和编译时期异常(CompilerException,代码编写时候就发生了异常 )
public class Code implements Serializable {
public static final Integer SAVE_OK = 20011;
public static final Integer DELETE_OK = 20021;
public static final Integer UPDATE_OK = 20031;
public static final Integer GET_OK = 20041;
public static final Integer SAVE_ERROR = 20010;
public static final Integer DELETE_ERROR = 20020;
public static final Integer UPDATE_ERROR = 20030;
public static final Integer GET_ERROR = 20040;
}
@Data
public class Result implements Serializable {
private Integer code;
private Object data;
private String message;
}
使用springmvc自定义一个异常统一处理类。让代码更容易维护。
@ControllerAdvice
@Component
public class ProjectException {
@ExceptionHandler(BusinessException.class)
@ResponseBody
public Result doBusinessException(BusinessException e) {
return new Result(e.getCode(), e.getMessage(), null);
}
}
public class BusinessException extends RuntimeException {
private Integer code;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public BusinessException(Integer code) {
super();
this.code = code;
}
public BusinessException(String message, Integer code) {
super(message);
this.code = code;
}
public BusinessException(String message, Throwable cause, Integer code) {
super(message, cause);
this.code = code;
}
public BusinessException(Throwable cause, Integer code) {
super(cause);
this.code = code;
}
protected BusinessException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace, Integer code) {
super(message, cause, enableSuppression, writableStackTrace);
this.code = code;
}
}
期异常
public class SysteamException extends RuntimeException {
private Integer code;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public SysteamException(Integer code) {
super();
this.code = code;
}
public SysteamException(String message,Integer code) {
super(message);
this.code = code;
}
public SysteamException(String message, Throwable cause,Integer code) {
super(message, cause);
this.code = code;
}
public SysteamException(Throwable cause,Integer code) {
super(cause);
this.code = code;
}
protected SysteamException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace,Integer code) {
super(message, cause, enableSuppression, writableStackTrace);
this.code = code;
}
}
对代码进行检测
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
private OrderService orderService;
@GetMapping("/{uuid}")
public Result get(@PathVariable Integer uuid) {
System.out.println("get...." + uuid);
if (uuid==4) throw new BusinessException("错误", Code.GET_ERROR);
User user = userService.get(uuid);
return new Result(user != null ? Code.GET_OK : Code.GET_ERROR, user, null);
}
}