统一结果返回 目前的前后端开发大部分数据的传输格式都是json,因此定义一个统一规范的数据格式有利于前后端的交互与UI的展示。
统一结果的一般形式
package com.codervibe.demo.common.response;
import lombok.Data;
import java.util.HashMap;
import java.util.Map;
@Data
public class R {
private Boolean success;
private Integer code;
private String message;
private Map<String, Object> data = new HashMap<>();
// 构造器私有
private R() {
}
// 通用返回成功
public static R ok() {
R r = new R();
r.setSuccess(ResultCodeEnum.SUCCESS.getSuccess());
r.setCode(ResultCodeEnum.SUCCESS.getCode());
r.setMessage(ResultCodeEnum.SUCCESS.getMessage());
return r;
}
// 通用返回失败,未知错误
public static R error() {
R r = new R();
r.setSuccess(ResultCodeEnum.UNKNOWN_ERROR.getSuccess());
r.setCode(ResultCodeEnum.UNKNOWN_ERROR.getCode());
r.setMessage(ResultCodeEnum.UNKNOWN_ERROR.getMessage());
return r;
}
// 设置结果,形参为结果枚举
public static R setResult(ResultCodeEnum result) {
R r = new R();
r.setSuccess(result.getSuccess());
r.setCode(result.getCode());
r.setMessage(result.getMessage());
return r;
}
/**
* ------------使用链式编程,返回类本身-----------
**/
// 自定义返回数据
public R data(Map<String, Object> map) {
this.setData(map);
return this;
}
// 通用设置data
public R data(String key, Object value) {
this.data.put(key, value);
return this;
}
// 自定义状态信息
public R message(String message) {
this.setMessage(message);
return this;
}
// 自定义状态码
public R code(Integer code) {
this.setCode(code);
return this;
}
// 自定义返回结果
public R success(Boolean success) {
this.setSuccess(success);
return this;
}
}
package com.codervibe.demo.common.response;
import lombok.Getter;
@Getter
public enum ResultCodeEnum {
SUCCESS(true,20000,"成功"),
UNKNOWN_ERROR(false,20001,"未知错误"),
PARAM_ERROR(false,20002,"参数错误"),
NULL_POINT(false,20003,"空指针错误"),
HTTP_CLIENT_ERROR(false,20004,"客户端错误")
;
private Boolean success;
private Integer code;
private String message;
ResultCodeEnum(boolean success,Integer code,String message){
this.success =success;
this.code = code;
this.message =message;
}
}
package com.codervibe.demo.model;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.experimental.Accessors;
import java.util.Date;
/**
* Created by Administrator on 2022/3/3 0003
* DateTime:2022/03/03 14:24
* Description:
* Others:
* @author Administrator
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Accessors(chain = true)
public class User {
private int id;
/**
* 用户名
*/
private String username;
/**
* 密码
*/
private String password;
/**
* 邮箱
*/
private String email;
/**
* 创建时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private Date createTime;
/**
* 角色访问权限
*/
private String role;
private static final long serialVersionUID = 1L;
}
package com.codervibe.demo.controller;
import com.codervibe.demo.common.response.R;
import com.codervibe.demo.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserController {
Logger logger = LoggerFactory.getLogger(UserController.class);
@GetMapping("/list")
public R list() {
// 这里实际上应该是从 数据库中查询出来 但是 我为了省事所以就直接创建了一个 用户列表
// 从数据库中查询出来 实际上效果是一样的
List<User> userList = new ArrayList<>();
userList.add(new User(1, "孙悟空", "1111", "[email protected]", new Date(), "1"));
userList.add(new User(2, "金蝉子", "1111", "[email protected]", new Date(), "1"));
userList.add(new User(3, "鲁班七号", "11111", "[email protected]", new Date(), "1"));
userList.add(new User(4, "鲁班大师", "11111", "[email protected]", new Date(), "1"));
userList.add(new User(5, "安其拉", "111111", "[email protected]", new Date(), "1"));
// 使用 log4j 做日志打印
logger.info("用户列表 :"+userList.toString());
return R.ok().data("userItems", userList).message("用户列表");
}
}
C:\Users\Administrator\Desktop>curl http://localhost:5767/demo/user/list
{
"success": true,
"code": 20000,
"message": "用户列表",
"data": {
"userItems": [
{
"id": 1,
"username": "孙悟空",
"password": "1111",
"email": "[email protected]",
"createTime": "2024-01-20 23:14:44",
"role": "1"
},
{
"id": 2,
"username": "金蝉子",
"password": "1111",
"email": "[email protected]",
"createTime": "2024-01-20 23:14:44",
"role": "1"
},
{
"id": 3,
"username": "鲁班七号",
"password": "11111",
"email": "[email protected]",
"createTime": "2024-01-20 23:14:44",
"role": "1"
},
{
"id": 4,
"username": "鲁班大师",
"password": "11111",
"email": "[email protected]",
"createTime": "2024-01-20 23:14:44",
"role": "1"
},
{
"id": 5,
"username": "安其拉",
"password": "111111",
"email": "[email protected]",
"createTime": "2024-01-20 23:14:44",
"role": "1"
}
]
}
}
package com.codervibe.demo.common.exception;
import com.codervibe.demo.common.response.ResultCodeEnum;
import lombok.Data;
@Data
public class DemoException extends RuntimeException{
private Integer code;
public DemoException(Integer code, String message) {
super(message);
this.code = code;
}
public DemoException(ResultCodeEnum resultCodeEnum) {
super(resultCodeEnum.getMessage());
this.code = resultCodeEnum.getCode();
}
@Override
public String toString() {
return "DemoException{" + "code=" + code + ", message=" + this.getMessage() + '}';
}
}
package com.codervibe.demo.common.exception;
import com.codervibe.demo.common.response.R;
import com.codervibe.demo.common.response.ResultCodeEnum;
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.client.HttpClientErrorException;
@ControllerAdvice
public class GlobalExceptionHandler {
/**-------- 通用异常处理方法 --------**/
@ExceptionHandler(Exception.class)
@ResponseBody
public R error(Exception e) {
e.printStackTrace();
return R.error(); // 通用异常结果
}
/**-------- 指定异常处理方法 --------**/
@ExceptionHandler(NullPointerException.class)
@ResponseBody
public R error(NullPointerException e) {
e.printStackTrace();
return R.setResult(ResultCodeEnum.NULL_POINT);
}
@ExceptionHandler(HttpClientErrorException.class)
@ResponseBody
public R error(IndexOutOfBoundsException e) {
e.printStackTrace();
return R.setResult(ResultCodeEnum.HTTP_CLIENT_ERROR);
}
/**-------- 自定义定异常处理方法 --------**/
@ExceptionHandler(DemoException.class)
@ResponseBody
public R error(DemoException e) {
e.printStackTrace();
return R.error().message(e.getMessage()).code(e.getCode());
}
}
{
"success": false,
"code": 20007,
"message": "空指针异常",
"data": {}
}