Quellcode durchsuchen

add:统一结果+统一异常v1

tujidelv vor 3 Jahren
Ursprung
Commit
56abc1da0a

+ 0 - 24
src/main/java/top/lvzhiqiang/config/GlobalExceptionHandler.java

@@ -1,24 +0,0 @@
-package top.lvzhiqiang.config;
-
-import org.springframework.web.bind.annotation.ControllerAdvice;
-import org.springframework.web.bind.annotation.ExceptionHandler;
-import org.springframework.web.bind.annotation.ResponseBody;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * 全局捕获异常
- */
-@ControllerAdvice(basePackages = "top.lvzhiqiang.controller")
-public class GlobalExceptionHandler {
-
-    @ExceptionHandler(RuntimeException.class)
-    @ResponseBody
-    public Map<String, Object> exceptionHandler() {
-        Map<String, Object> map = new HashMap<>();
-        map.put("errorCode", "101");
-        map.put("errorMsg", "系統错误!");
-        return map;
-    }
-}

+ 107 - 0
src/main/java/top/lvzhiqiang/config/UnifiedReturnConfig.java

@@ -0,0 +1,107 @@
+package top.lvzhiqiang.config;
+
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.core.MethodParameter;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.http.converter.HttpMessageConverter;
+import org.springframework.http.server.ServerHttpRequest;
+import org.springframework.http.server.ServerHttpResponse;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.RestControllerAdvice;
+import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
+import top.lvzhiqiang.dto.R;
+import top.lvzhiqiang.exception.BusinessException;
+import top.lvzhiqiang.exception.ParameterException;
+
+/**
+ * 通用返回配置类
+ *
+ * @author lvzhiqiang
+ * 2022/4/11 16:55
+ */
+@Configuration
+@Slf4j
+public class UnifiedReturnConfig {
+
+    /**
+     * 统一返回数据格式
+     *
+     * @author lvzhiqiang
+     * 2022/4/11 16:55
+     */
+    @RestControllerAdvice("top.lvzhiqiang.controller")
+    static class CommonResultResponseAdvice implements ResponseBodyAdvice<Object> {
+        @Override
+        public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
+            return true;
+        }
+
+        @Override
+        public Object beforeBodyWrite(Object body, MethodParameter methodParameter,
+                                      MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass,
+                                      ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
+
+            if (body instanceof R) {
+                return body;
+            }
+
+            return R.ok().data(body);
+        }
+    }
+
+    /**
+     * 统一异常处理
+     *
+     * @author shiyong
+     * 2019-10-08 17:19
+     */
+    @RestControllerAdvice("top.lvzhiqiang.controller")
+    static class UnifiedExceptionHandler {
+
+        /**
+         * 处理通用异常
+         *
+         * @param e 异常
+         * @return org.springframework.http.ResponseEntity<top.lvzhiqiang.dto.R>
+         * @author lvzhiqiang
+         * 2021/4/11 23:04
+         */
+        @ExceptionHandler(Exception.class)
+        public ResponseEntity<R<Void>> handleException(Exception e) {
+            log.error("服务器异常!", e);
+
+            return new ResponseEntity<>(R.error(), HttpStatus.INTERNAL_SERVER_ERROR);
+        }
+
+        /**
+         * 处理业务异常
+         *
+         * @param e 业务异常
+         * @return org.springframework.http.ResponseEntity<top.lvzhiqiang.dto.R>
+         * @author lvzhiqiang
+         * 2021/4/11 23:04
+         */
+        @ExceptionHandler(BusinessException.class)
+        public ResponseEntity<R<Void>> handleBusinessException(BusinessException e) {
+
+            return new ResponseEntity<>(R.error().message(e.getMessage()).code(e.getCode()), HttpStatus.OK);
+        }
+
+        /**
+         * 处理参数异常
+         *
+         * @param e 参数异常
+         * @return org.springframework.http.ResponseEntity<top.lvzhiqiang.dto.R>
+         * @author lvzhiqiang
+         * 2021/4/11 23:04
+         */
+        @ExceptionHandler(ParameterException.class)
+        public ResponseEntity<R<Void>> handleParameterException(ParameterException e) {
+
+            return new ResponseEntity<>(R.error().message(e.getMessage()).code(e.getCode()), HttpStatus.OK);
+        }
+    }
+}

+ 1 - 1
src/main/java/top/lvzhiqiang/controller/IndexController.java

@@ -9,8 +9,8 @@ import top.lvzhiqiang.entity.VideoCast;
 import top.lvzhiqiang.entity.VideoGenres;
 import top.lvzhiqiang.entity.VideoInfo;
 import top.lvzhiqiang.service.VideoCastService;
-import top.lvzhiqiang.service.VideoInfoService;
 import top.lvzhiqiang.service.VideoGenresService;
+import top.lvzhiqiang.service.VideoInfoService;
 
 import javax.annotation.Resource;
 import java.util.List;

+ 80 - 0
src/main/java/top/lvzhiqiang/dto/R.java

@@ -0,0 +1,80 @@
+package top.lvzhiqiang.dto;
+
+import lombok.Data;
+import top.lvzhiqiang.enumeration.ResultCodeEnum;
+
+/**
+ * 统一结果类
+ *
+ * @author lvzhiqiang
+ * 2022/4/11 16:55
+ */
+@Data
+public class R<T> {
+    private Boolean success;
+
+    private Integer code;
+
+    private String message;
+
+    private T data;
+
+    // 构造器私有
+    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(T data) {
+        this.setData(data);
+        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;
+    }
+}

+ 30 - 0
src/main/java/top/lvzhiqiang/enumeration/ResultCodeEnum.java

@@ -0,0 +1,30 @@
+package top.lvzhiqiang.enumeration;
+
+import lombok.Getter;
+
+/**
+ * 结果类枚举
+ *
+ * @author lvzhiqiang
+ * 2022/4/11 16:55
+ */
+@Getter
+public enum ResultCodeEnum {
+    SUCCESS(true, 20000, "成功"),
+    UNKNOWN_ERROR(false, 20001, "未知错误"),
+    PARAM_ERROR(false, 20002, "参数错误"),
+    ;
+
+    // 响应是否成功
+    private final Boolean success;
+    // 响应状态码
+    private final Integer code;
+    // 状态码描述
+    private final String message;
+
+    ResultCodeEnum(boolean success, Integer code, String message) {
+        this.success = success;
+        this.code = code;
+        this.message = message;
+    }
+}

+ 26 - 0
src/main/java/top/lvzhiqiang/exception/BusinessException.java

@@ -0,0 +1,26 @@
+package top.lvzhiqiang.exception;
+
+import lombok.Data;
+import top.lvzhiqiang.enumeration.ResultCodeEnum;
+
+/**
+ * 业务异常
+ *
+ * @author lvzhiqiang
+ * 2021/4/11 23:04
+ */
+@Data
+public class BusinessException extends RuntimeException {
+
+    private Integer code;
+
+    public BusinessException(Integer code, String message) {
+        super(message);
+        this.code = code;
+    }
+
+    public BusinessException(ResultCodeEnum resultCodeEnum) {
+        super(resultCodeEnum.getMessage());
+        this.code = resultCodeEnum.getCode();
+    }
+}

+ 26 - 0
src/main/java/top/lvzhiqiang/exception/ParameterException.java

@@ -0,0 +1,26 @@
+package top.lvzhiqiang.exception;
+
+import lombok.Data;
+import top.lvzhiqiang.enumeration.ResultCodeEnum;
+
+/**
+ * 参数异常
+ *
+ * @author lvzhiqiang
+ * 2021/4/11 23:04
+ */
+@Data
+public class ParameterException extends RuntimeException {
+
+    private Integer code;
+
+    public ParameterException(Integer code, String message) {
+        super(message);
+        this.code = code;
+    }
+
+    public ParameterException(ResultCodeEnum resultCodeEnum) {
+        super(resultCodeEnum.getMessage());
+        this.code = resultCodeEnum.getCode();
+    }
+}

+ 18 - 12
src/main/resources/static/js/my.js

@@ -17,7 +17,8 @@ $(function () {
         async: true, //请求是否异步,默认为异步,这也是ajax重要特性
         success: function (data) {
             //请求成功时处理
-            if (data != null && $.trim(data) != "") {
+            if (data != null && $.trim(data) != "" && data.success) {
+                data = data.data;
                 if (data.videoCastList.length > 0) {
                     var videoCastList = data.videoCastList;
                     var str = "";
@@ -89,6 +90,8 @@ $(function () {
                         }
                     });
                 }
+            } else {
+                alert(data.message);
             }
         },
         beforeSend: function () {
@@ -99,16 +102,16 @@ $(function () {
             //请求完成的处理
             $("#cover").css('display', 'none');
         },
-        error: function (errorData) {
+        error: function (data) {
             //请求出错处理
-            alert('error:' + errorData);
+            alert('error:' + data);
         }
     });
 
     $("#searchbutton").click(function () {
         search(1);
     });
-    $("#shaixuan").click(function (){
+    $("#shaixuan").click(function () {
         $("#wd").val("");
 
         search(1);
@@ -118,14 +121,14 @@ $(function () {
             search(1);
         }
     });
-    $(".dropdown-box").find("li").click(function (){
+    $(".dropdown-box").find("li").click(function () {
         $("#bigType").text($(this).text());
         $(".dropdown-box").attr("style", "display: none;");
     });
-    $(".dropdown-hover").mouseover(function(){
+    $(".dropdown-hover").mouseover(function () {
         $(".dropdown-box").attr("style", "display: block;");
     });
-    $(".dropdown-hover").mouseout(function(){
+    $(".dropdown-hover").mouseout(function () {
         $(".dropdown-box").attr("style", "display: none;");
     });
 });
@@ -153,7 +156,8 @@ function search(pageNo) {
         async: true, //请求是否异步,默认为异步,这也是ajax重要特性
         success: function (data) {
             //请求成功时处理
-            if (data != null && $.trim(data) != "") {
+            if (data != null && $.trim(data) != "" && data.success) {
+                data = data.data;
                 var videoInfoList = data.list;
                 var str = "";
                 for (var i = 0; i < videoInfoList.length; i++) {
@@ -199,19 +203,21 @@ function search(pageNo) {
                         search(pageNo);
                     }
                 });
+            } else {
+                alert(data.message);
             }
         },
         beforeSend: function () {
             //请求前的处理
-            $(".loading").css("display","block");
+            $(".loading").css("display", "block");
         },
         complete: function () {
             //请求完成的处理
-            $(".loading").css("display","none");
+            $(".loading").css("display", "none");
         },
-        error: function (errorData) {
+        error: function (data) {
             //请求出错处理
-            alert('error:' + errorData);
+            alert('error:' + data);
         }
     });
 }