数据的封装
package com.dolist.config;
public class JsonResult {
private Integer code;
private String msg;
private Object data;
public static JsonResult success(Object data) {
JsonResult js = new JsonResult();
js.setCode(200);
js.setData(data);
return js;
}
public static JsonResult success(Object data, String msg) {
JsonResult js = new JsonResult();
js.setCode(200);
js.setData(data);
js.setMsg(msg);
return js;
}
public static JsonResult fail(Integer code, String msg) {
JsonResult js = new JsonResult();
js.setCode(code);
js.setMsg(msg);
return js;
}
//get,set方法
}
全局自定义异常处理
功能模块异常枚举类
不同的功能模块抛出异常可能不一样,举例用户的异常
package com.dolist.exception;
public enum UserExceptionEnum {
USER_NO_EXITS(201, "用户不存在"),
COUNT_HAVE_EXITS(202, "用户名已存在"),
PWD_NO_MATCH(203, "密码不匹配"),
INSERT_ERROR(204, "添加数据失败"),
UPDATE_ERROR(205, "更新数据失败"),
DELETE_ERROR(206, "删除数据失败");
private Integer code;
private String msg;
UserExceptionEnum(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public Integer getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
全局异常类
随后需要定义一个类去管理所有的异常
package com.dolist.exception;
public class AppException extends RuntimeException {
private Integer code;
private String msg;
public AppException(Integer code, String msg) {
super();
this.code = code;
this.msg = msg;
}
public AppException(UserExceptionEnum userExceptionEnum) {
super();
this.code = userExceptionEnum.getCode();
this.msg = userExceptionEnum.getMsg();
}
public AppException(TaskExceptionEnum taskExceptionEnum) {
super();
this.code = taskExceptionEnum.getCode();
this.msg = taskExceptionEnum.getMsg();
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
全局异常处理类
package com.dolist.exception;
import com.dolist.config.JsonResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = {Exception.class})
@ResponseBody
public JsonResult exceptionHandler(Exception e) {
if (e instanceof AppException) {
AppException appException = (AppException) e;
return JsonResult.fail(appException.getCode(), appException.getMsg());
}
return JsonResult.fail(500, e.getMessage());
}
}
时间格式的处理
依赖
<!-- 日期格式化 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
<version>1.5.2.RELEASE</version>
</dependency>
配置
spring:
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
```