1、创建自定义的异常RRException
package com.blog.common.utils;
public class RRException extends RuntimeException {
private static final long serialVersionUID = 1L;
private String msg;
private int code = 500;
private Object data;
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public RRException(String msg) {
super(msg);
this.msg = msg;
}
public RRException(String msg, Throwable e) {
super(msg, e);
this.msg = msg;
}
public RRException(String msg, int code) {
super(msg);
this.msg = msg;
this.code = code;
}
public RRException(String msg, int code, Throwable e) {
super(msg, e);
this.msg = msg;
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}
2、创建异常处理配置类MyExceptionHandler
package com.blog.index.config;
import com.blog.common.result.R;
import com.blog.common.utils.RRException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
public class MyExceptionHandler {
@ResponseBody
@ExceptionHandler(value = Exception.class)
public Object errorHandler(Exception e){
e.printStackTrace();
return R.error(110, e.getMessage());
}
@ResponseBody
@ExceptionHandler(value = RRException.class)
public Object myErrorHandler(RRException e){
e.printStackTrace();
return R.error(e.getCode(), e.getMsg());
}
}
3、在代码中手动抛出异常即可
throw new RRException("该用户没有权限!", 504);
4、返回效果
{"msg":"该用户没有权限!","code":504,"needRefresh":true}