有的时候对于一些特殊的异常,我们需要进行别人的处理,那怎么自定义我们的异常的?
//这里可继承你需要定义的错误
public class CustomException extends RuntimeException {
//可以用来接受我们方法中传的参数
private String code;
private String msg;
public CustomException(String code,String msg) {
//super("Token异常,请重新登录");
this.code = code;
this.msg=msg;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
在你需要的地方直接抛出这个异常
if (token == null||token.equals("")) {
//throw new RuntimeException("未认证,请检查token,请重新登录");
logger.error("401未认证请检查token");
throw new CustomException("401","未认证请检查token");
}
这个接口是要给app调用的,对于app来说需要定义统一的接受格式,不然没有办法拿到返回的数据,所以我们需要定义自己的异常返回类型
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import java.util.HashMap;
import java.util.Map;
@ControllerAdvice
public class ControllerHanderException {
@ExceptionHandler(CustomException.class)
@ResponseBody
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
//在这个方法里定义我们需要返回的格式
public Map<String, Object> handleUserNotExistException(CustomException ex){
Map<String, Object> result = new HashMap<>();
result.put("code", ex.getCode()); //获取到我们定义的code
result.put("msg", ex.getMsg()); //获取到我们定义的msg
//result.put("message", ex.getMessage());
return result;
}
}