有的时候对于一些特殊的异常,我们需要进行别人的处理,那怎么自定义我们的异常的?
public class CustomException extends RuntimeException {
private String code;
private String msg;
public CustomException(String code,String msg) {
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("")) {
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());
result.put("msg", ex.getMsg());
return result;
}
}
@ControllerAdvice注解表示这个Controller不处理http请求,只处理当其他controller抛出异常时,进行处理。
@ExceptionHandler: 就是定义处理什么异常
