|
|
@@ -0,0 +1,69 @@
|
|
|
+package space.anyi.serve.handler;
|
|
|
+
|
|
|
+import jakarta.validation.ConstraintViolationException;
|
|
|
+import org.springframework.http.HttpStatus;
|
|
|
+import org.springframework.validation.BindException;
|
|
|
+import org.springframework.validation.FieldError;
|
|
|
+import org.springframework.web.bind.MethodArgumentNotValidException;
|
|
|
+import org.springframework.web.bind.annotation.ExceptionHandler;
|
|
|
+import org.springframework.web.bind.annotation.ResponseStatus;
|
|
|
+import org.springframework.web.bind.annotation.RestControllerAdvice;
|
|
|
+import org.springframework.web.servlet.View;
|
|
|
+import space.anyi.serve.entity.Response;
|
|
|
+
|
|
|
+import java.util.List;
|
|
|
+import java.util.stream.Collectors;
|
|
|
+
|
|
|
+/**
|
|
|
+ * @fileName: GlobalExceptionHandler
|
|
|
+ * @projectName: serve
|
|
|
+ * @package: space.anyi.serve.handler
|
|
|
+ * @author: 杨逸
|
|
|
+ * @date:2026/4/29 17:01
|
|
|
+ * @description: 全局异常处理
|
|
|
+ */
|
|
|
+@RestControllerAdvice
|
|
|
+public class GlobalExceptionHandler {
|
|
|
+
|
|
|
+
|
|
|
+ // 处理参数校验失败异常
|
|
|
+ @ExceptionHandler(MethodArgumentNotValidException.class)
|
|
|
+ @ResponseStatus(HttpStatus.BAD_REQUEST)
|
|
|
+ public Response<List<FieldError>> handleValidationExceptions(MethodArgumentNotValidException ex) {
|
|
|
+ List<FieldError> fieldErrors = ex.getFieldErrors()
|
|
|
+ .stream()
|
|
|
+ .map(error -> new FieldError(error.getObjectName(),error.getField(),error.getDefaultMessage()))
|
|
|
+ .collect(Collectors.toList());
|
|
|
+
|
|
|
+ return Response.error("参数不合法",fieldErrors);
|
|
|
+ }
|
|
|
+
|
|
|
+ // 处理单个参数校验失败
|
|
|
+ @ExceptionHandler(ConstraintViolationException.class)
|
|
|
+ @ResponseStatus(HttpStatus.BAD_REQUEST)
|
|
|
+ public Response<List<FieldError>> handleConstraintViolation(ConstraintViolationException ex) {
|
|
|
+ List<FieldError> fieldErrors = ex.getConstraintViolations()
|
|
|
+ .stream()
|
|
|
+ .map(violation -> new FieldError(null,violation.getPropertyPath().toString(),violation.getMessage()))
|
|
|
+ .collect(Collectors.toList());
|
|
|
+
|
|
|
+ return Response.error("参数不合法",fieldErrors);
|
|
|
+ }
|
|
|
+
|
|
|
+ // 处理 @Validated 分组校验异常
|
|
|
+ @ExceptionHandler(BindException.class)
|
|
|
+ @ResponseStatus(HttpStatus.BAD_REQUEST)
|
|
|
+ public Response<List<FieldError>> handleBindException(BindException ex) {
|
|
|
+ List<FieldError> fieldErrors = ex.getFieldErrors()
|
|
|
+ .stream()
|
|
|
+ .map(error -> new FieldError( error.getObjectName(),error.getField(), error.getDefaultMessage()))
|
|
|
+ .collect(Collectors.toList());
|
|
|
+
|
|
|
+ return Response.error("参数不合法",fieldErrors);
|
|
|
+ }
|
|
|
+
|
|
|
+ @ExceptionHandler(Exception.class)
|
|
|
+ public Response handlerException(Exception e){
|
|
|
+ return Response.error(e.getMessage());
|
|
|
+ }
|
|
|
+}
|