Procházet zdrojové kódy

feat:添加接口全局统一异常处理

liuchuanwei před 2 měsíci
rodič
revize
a267b99bab

+ 1 - 1
src/main/java/com/anyway/favor/BusinessException.java → src/main/java/com/anyway/exception/BusinessException.java

@@ -1,4 +1,4 @@
-package com.anyway.favor;
+package com.anyway.exception;
 
 /**
  * 业务异常

+ 36 - 0
src/main/java/com/anyway/exception/GlobalExceptionHandler.java

@@ -0,0 +1,36 @@
+package com.anyway.exception;
+
+import com.anyway.util.R;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.validation.ObjectError;
+import org.springframework.web.bind.MethodArgumentNotValidException;
+import org.springframework.web.bind.annotation.ControllerAdvice;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.ResponseBody;
+
+import java.util.stream.Collectors;
+
+/**
+ * @Description: 全局异常处理器
+ *
+ * @author liuchuanwei
+ * @date 2024-08-13
+ */
+@Slf4j
+@ControllerAdvice
+public class GlobalExceptionHandler {
+    @ExceptionHandler(MethodArgumentNotValidException.class)
+    @ResponseBody
+    public R<Void> handleValidException(MethodArgumentNotValidException e){
+        log.error("参数校验失败:{}", e.getMessage(), e);
+        String errorMessages = e.getBindingResult().getAllErrors().stream().map(ObjectError::getDefaultMessage).collect(Collectors.joining(";"));
+        return R.fail(errorMessages);
+    }
+
+    @ExceptionHandler(RuntimeException.class)
+    @ResponseBody
+    public R<Void> handleRuntimeException(RuntimeException e){
+        log.error("系统异常:{}", e.getMessage(), e);
+        return R.fail("系统异常:" + e.getMessage());
+    }
+}

+ 1 - 1
src/main/java/com/anyway/favor/service/impl/FavorServiceImpl.java

@@ -1,6 +1,6 @@
 package com.anyway.favor.service.impl;
 
-import com.anyway.favor.BusinessException;
+import com.anyway.exception.BusinessException;
 import com.anyway.favor.dao.FavorDao;
 import com.anyway.favor.dao.FavorItemDao;
 import com.anyway.favor.dao.GiftDao;