一、@ControllerAdvice注解
把@ControllerAdvice注解内部使用@ExceptionHandler、@InitBinder、@ModelAttribute注解的方法应用到所有的 @RequestMapping注解的方法。
如果方法抛出异常,BizExceptionHandler找到匹配的入参,调用方法,把信息写入Response对象,返回。
如果正常返回数据,ResponseHandler经过判断,把信息写入Response对象,返回。
二、Response类
将返回值写入Response类返回。
@Data
public class Response {
private String code;
private String message;
private Object data;
public Response() {
}
public Response(String code, String message) {
this.code = code;
this.message = message;
}
public static Response success(){
Response response = new Response();
response.code = "0";
response.setMessage("请求成功");
return response;
}
public static Response success(Object data) {
Response response = new Response();
response.setCode("0");
response.setMessage("请求成功");
response.setData(data);
return response;
}
public static Response error(String code, String message) {
Response response = new Response(code, message);
return response;
}
}
三、异常处理
1.异常处理类(BizExceptionHandler)
用@ControllerAdvice注解注释这个异常处理类。
@ControllerAdvice
public class BizExceptionHandler {
private Logger logger = LogManager.getLogger(this.getClass());
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public Response all(Exception e) {
logger.error("Exception:", e);
return Response.error("10000", "未知错误,请联系相关管理人员");
}
@ExceptionHandler(BizRuntimeException.class) //入参,定义的异常类型
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) //返回的http状态码
@ResponseBody
public Response bizException(BizRuntimeException e) {
logger.warn("请求数据抛出逻辑异常:{}", e.getMessage());
return Response.error(e.getCode(), e.getMessage());
}
}
@ResponseStatus注解是修饰类的
它有两个属性,value属性是http状态码,比如404,500等。reason是错误信息
如:@ResponseStatus(value=HttpStatus.FORBIDDEN,reason=”用户不匹配”)
2.自定义异常类和常数类(异常Code和描述)
①自定义异常类(可以定义多个,通过Handler中不同入参区分)
public class BizRuntimeException extends RuntimeException {
private String code;
private String message;
public BizRuntimeException(String code) {
super(ExceptionConstant.getMessage(code));
this.code = code;
this.message = ExceptionConstant.getMessage(code);
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
②常数类
public abstract class ExceptionConstant {
private static Map message = new HashMap();
public static final String ACCOUNT_EXISTED = "5000";
public static final String PASSWORD_ERROR = "5001";
static {
message.put(ACCOUNT_EXISTED, "账号已存在");
message.put(PASSWORD_ERROR,"密码错误");
}
public static String getMessage(String code) {
return message.get(code);
}
}
③使用时:
throw new BizRuntimeException(ExceptionConstant.ACCOUNT_EXISTED);
四、ResponseHandler
1.ResponseHandler返回值处理类
@ControllerAdvice
public class ResponseHandler implements ResponseBodyAdvice