Pārlūkot izejas kodu

feat(utils): 添加自定义异常处理逻辑

- 新增 BusinessException 类作为通用终止异常
- 新增 ExceptionAdvice 类实现全局异常捕获和处理
- 优化异常处理逻辑,支持自定义状态码和错误信息
hechunping 2 mēneši atpakaļ
vecāks
revīzija
33446b3d49

+ 26 - 0
src/main/java/com/xynet/marketing/utils/error/BusinessException.java

@@ -0,0 +1,26 @@
+package com.xynet.marketing.utils.error;
+
+
+/**
+ * 通用终止异常
+ */
+public class BusinessException extends RuntimeException {
+
+    public BusinessException(String message) {
+        super(message);
+    }
+
+    public BusinessException(Integer status, String message) {
+        super(String.format("%d::%s", status, message));
+    }
+
+    public BusinessException(Throwable e) {
+        super(e);
+    }
+
+    public BusinessException(String msg, Throwable cause) {
+        super(msg, cause);
+    }
+
+
+}

+ 44 - 0
src/main/java/com/xynet/marketing/utils/error/ExceptionAdvice.java

@@ -0,0 +1,44 @@
+package com.xynet.marketing.utils.error;
+
+import com.xynet.marketing.utils.R;
+import lombok.AllArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.RestControllerAdvice;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+@Slf4j
+@AllArgsConstructor
+@RestControllerAdvice
+public class ExceptionAdvice {
+
+
+    /**
+     * 全局异常
+     *
+     * @param e
+     * @return
+     */
+    @ExceptionHandler(Exception.class)
+    public R allException(HttpServletRequest request, HttpServletResponse response, Exception e) {
+        log.error("", e);
+        return R.fail(R.Enum.FAIL.getCode(), e.getMessage());
+    }
+
+    /**
+     * 通用终止异常
+     *
+     * @param e
+     * @return
+     */
+    @ExceptionHandler(BusinessException.class)
+    public R businessException(BusinessException e) {
+        if (e.getMessage().indexOf("::") == -1) {
+            return R.fail(e.getMessage());
+        }
+        String[] split = e.getMessage().split("::");
+        return R.fail(Integer.parseInt(split[0]), split[1]);
+    }
+}