全局异常
创建异常处理类
@RestControllerAdvice //复合注解,标注为异常处理类,+ResponseBody
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public R error(Exception e){
e.printStackTrace();
return R.error().message("执行了Exception全局异常");
}
}
特殊异常
与全局异常类似,指定异常类为特殊的异常类
@RestControllerAdvice
public class GlobalExceptionHandler {
//特殊异常
@ExceptionHandler(ArithmeticException.class)
public R error(ArithmeticException e){
e.printStackTrace();
return R.error().message("执行了ArithmeticException特殊异常");
}
}
自定义异常
创建自定义异常类,继承RuntimeException
@Data
@AllArgsConstructor
@NoArgsConstructor
public class MyException extends RuntimeException {
@ApiModelProperty(value = "状态码")
private Integer code;
@ApiModelProperty(value = "错误消息")
private String msg;
}
在异常处理类中添加异常处理
@RestControllerAdvice
public class GlobalExceptionHandler {
//自定义异常
@ExceptionHandler(MyException.class)
public R error(MyException e){
e.printStackTrace();
return R.error().code(e.getCode()).message(e.getMsg());
}
}
使用自定义异常
try {
int i = 10/0;
} catch (Exception e) {
throw new MyException(20003,"自定义MyException错误异常");
}
R对象为预封装的返回统一结果值
统一返回对象
@Data
public class R {
@ApiModelProperty(value = "是否成功")
private Boolean success;
@ApiModelProperty(value = "返回码")
private Integer code;
@ApiModelProperty(value = "返回消息")
private String message;
@ApiModelProperty(value = "返回数据")
private Map<String, Object> data = new HashMap<String, Object>();
private R(){}
public static R ok(){
R r = new R();
r.setSuccess(true);
r.setCode(ResultCode.SUCCESS);
r.setMessage("成功");
return r;
}
public static R error(){
R r = new R();
r.setSuccess(false);
r.setCode(ResultCode.ERROR);
r.setMessage("失败");
return r;
}
public R success(Boolean success){
this.setSuccess(success);
return this;
}
public R message(String message){
this.setMessage(message);
return this;
}
public R code(Integer code){
this.setCode(code);
return this;
}
public R data(String key, Object value){
this.data.put(key, value);
return this;
}
public R data(Map<String, Object> map){
this.setData(map);
return this;
}
}
封装返回状态码与消息,常量
public interface ResultCode {
public static Integer SUCCESS = 200;
public static Integer ERROR = 4000;
}