You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
2.5 KiB

  1. package com.example.demo.domain.vo;
  2. import com.example.demo.Util.BusinessException;
  3. import com.fasterxml.jackson.core.JsonProcessingException;
  4. import com.fasterxml.jackson.databind.ObjectMapper;
  5. import lombok.AllArgsConstructor;
  6. import lombok.Data;
  7. import lombok.NoArgsConstructor;
  8. import java.io.Serializable;
  9. import java.util.HashMap;
  10. @Data
  11. @NoArgsConstructor
  12. @AllArgsConstructor
  13. public class Result implements Serializable {
  14. private static final long serialVersionUID = 1L;
  15. private Integer code; // 响应码,200 代表成功;401 代表未授权
  16. private String msg; // 响应消息
  17. private Object data; // 返回的数据
  18. // 成功响应(不需要给前端返回数据)
  19. public static Result success() {
  20. return new Result(200, "success", new HashMap<>());
  21. }
  22. // 查询成功响应(把查询结果作为返回数据响应给前端)
  23. public static Result success(Object data) {
  24. return new Result(200, "success", data);
  25. }
  26. // 失败响应
  27. public static Result error(String msg) {
  28. return new Result(0, msg, new HashMap<>());
  29. }
  30. // 失败响应,可以自定义错误码
  31. public static Result error(int code, String msg) {
  32. return new Result(code, msg, new HashMap<>());
  33. }
  34. // 成功响应,可以自定义消息和数据
  35. public static Result success(String msg, HashMap<String, Object> resultData) {
  36. return new Result(200, msg, resultData); // 返回成功响应,状态码为 200
  37. }
  38. // 未授权响应,可以自定义错误码
  39. public static Result unauthorized(int code, String msg) {
  40. return new Result(code, msg, new HashMap<>());
  41. }
  42. // 错误响应,状态码为200,code为401
  43. public static Result unauthorized(String msg) {
  44. return new Result(401, msg, new HashMap<>());
  45. }
  46. //失败响应 自定义状态码 默认为500
  47. public static Result error(BusinessException e) {
  48. Result response = new Result();
  49. // 定义默认错误码映射
  50. final int defaultErrorCode = 400;
  51. // 检查 getCode() 是否为 null(如果是 Integer)
  52. Integer code = e.getCode();
  53. if (code == null || code == 0) {
  54. response.setCode(defaultErrorCode); // 默认错误码
  55. } else {
  56. response.setCode(code);
  57. }
  58. response.setMsg(e.getMessage());
  59. return response;
  60. }
  61. public String toJson() throws JsonProcessingException {
  62. ObjectMapper mapper = new ObjectMapper();
  63. return mapper.writeValueAsString(this);
  64. }
  65. }