-
服务响应对象
ServerResponse
/**
* 服务响应类
* Created by gf on 2018/10/20.
*/
//保证序列化json的时候,如果是null的对象,key也会消失
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class ServerResponse implements Serializable{
private int code; //状态码
private String msg; //描述
private T data; //对象
private ServerResponse(int code) {
this.code = code;
}
private ServerResponse(int code, String msg) {
this.code = code;
this.msg = msg;
}
private ServerResponse(int code, String msg, T data) {
this.code = code;
this.msg = msg;
this.data = data;
}
private ServerResponse(int code, T data) {
this.code = code;
this.data = data;
}
/**
* 判断这个响应是否是一个成功的响应
* @return
*/
@JsonIgnore //使这个方法的返回值不在Json序列化结果当中
public boolean isSuccess(){
return this.code==ResponseCode.SUCCESS.getCode();
}
public int getCode() {
return code;
}
public String getMsg() {
return msg;
}
public T getData() {
return data;
}
/**
* 单例模式 创建返回响应对象
*/
public static ServerResponse createBySuccess(){
return new ServerResponse(ResponseCode.SUCCESS.getCode());
}
public static ServerResponse createBySuccessMessage(String msg){
return new ServerResponse(ResponseCode.SUCCESS.getCode(),msg);
}
public static ServerResponse createBySuccessData(T data){
return new ServerResponse(ResponseCode.SUCCESS.getCode(),data);
}
public static ServerResponse createBySuccessMsgData(String msg,T data){
return new ServerResponse(ResponseCode.SUCCESS.getCode(),msg,data);
}
public static ServerResponse createByError(){
return new ServerResponse(ResponseCode.ERROR.getCode(),ResponseCode.ERROR.getDesc());
}
public static ServerResponse createByErrorMessage(String errorMsg){
return new ServerResponse(ResponseCode.ERROR.getCode(),errorMsg);
}
public static ServerResponse createByErrorCodeMessage(int errorCode,String errorMsg){
return new ServerResponse(errorCode,errorMsg);
}
}
ResponseCode 枚举常量类
/**
* 枚举常量
* Created by gf on 2018/10/20.
*/
public enum ResponseCode {
SUCCESS(0,"SUCCESS"),
ERROR(1,"ERROR"),
NEED_LOGIN(10,"NEED_LOGIN"),
ILLEGAL_ARGUMENT(20,"ILLEGAL_ARGUMENT");
private int code;
private String desc;
ResponseCode(int code, String desc) {
this.code = code;
this.desc = desc;
}
public int getCode() {
return code;
}
public String getDesc() {
return desc;
}
}
Controller方法中的应用
/**
* 添加
* @return
*/
@PostMapping(value = "/add")
public ServerResponse addStudent(@Valid Student student,
BindingResult bindingResult){
if(bindingResult.hasErrors())
return ServerResponse.createByErrorMessage(bindingResult.getFieldError().getDefaultMessage());
return ServerResponse.createBySuccessData(studentRepository.save(student));
}
-
统一异常处理
自定义异常
应用场景:JDK中的异常类型不能满足程序的需要时,可以自定义异常
实现方式:继承Exception和RunTimeException
Spring framework 针对RuntimeException
才会进行事务回滚
public class StudentException extends RuntimeException {
private int code;
public StudentException(int code,String exceptionMsg) {
super(exceptionMsg);
this.code = code;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}
异常捕获
@ControllerAdvice + @ExceptionHandler 全局处理 Controller 层异常
@ControllerAdvice
标注的类为异常处理类
@ExceptionHandler(value = Exception.class)
标注的当前方法为异常处理方法
@ControllerAdvice //标注的类为异常处理类
public class ExceptionHandle {
private static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);
@ExceptionHandler(value = Exception.class) //标注的当前方法为异常处理方法
@ResponseBody
private ServerResponse handle(Exception e){
if(e instanceof StudentException){
StudentException se = (StudentException)e;
return ServerResponse.createByErrorCodeMessage(se.getCode(),se.getMessage());
}
logger.info("【异常信息】",e.toString());
return ServerResponse.createByErrorCodeMessage(ResponseCode.ERROR_EXCEPTION.getCode(),ResponseCode.ERROR_EXCEPTION.getDesc());
}
}
抛出异常
public ServerResponse> findByAge(Integer age) throws StudentException {
if(age<10)
throw new StudentException(StudentExceptionCode.PRIMARY_SCHOOL);
else if (age>10&&age<15)
throw new StudentException(StudentExceptionCode.MIDDLE_SCHOOL);
return ServerResponse.createBySuccessData(studentRepository.findByAge(age));
}
项目地址:https://gitee.com/goofyw/spring-boot-demo1/tree/v1.2/