平时用的自定义异常类
@Data
public class R {
private boolean success;
private Integer code;
private String message;
private Map<String,Object> data=new HashMap<>();
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.success(success);
return this;
}
public R error(boolean success){
this.success(false);
return this;
}
public R message(String message){
this.message=message;
return this;
}
public R code(Integer message){
this.code=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;
}
}
ResultCode接口
public interface ResultCode {
public static Integer SUCCESS = 20000;
public static Integer ERROR = 20001;
}
-------------全局异常类
自定义异常类继承RuntimeException
* 自定义异常类
*/
@Data
@AllArgsConstructor //有参数构造器
@NoArgsConstructor //生成无参数构造
public class GuoxueException extends RuntimeException {
private Integer code;//状态码
private String msg;//输出消息
}
自定义的异常处理类
@ControllerAdvice
public class GlobalExceptionHandler {
//自定义的异常处理
@ResponseBody//返回json数据
//@ExceptionHandler:监控某一个类,当该类出现异常,调用此方法
@ExceptionHandler(GuoxueException.class)
public R error(GuoxueException e){
//log.error(e.getMessage());
e.printStackTrace();
return R.error().code(e.getCode()).message(e.getMsg());
}
|