From 87a0ccb7ed3f0c9bfd856169ef03de136cd1047d Mon Sep 17 00:00:00 2001 From: tj <1378534974@qq.com> Date: 星期四, 20 三月 2025 09:07:39 +0800 Subject: [PATCH] 高级安全防护 --- src/main/java/com/jsh/erp/exception/GlobalExceptionHandler.java | 16 ++++++++++++++++ 1 files changed, 16 insertions(+), 0 deletions(-) diff --git a/src/main/java/com/jsh/erp/exception/GlobalExceptionHandler.java b/src/main/java/com/jsh/erp/exception/GlobalExceptionHandler.java index 5cc0b58..03eb931 100644 --- a/src/main/java/com/jsh/erp/exception/GlobalExceptionHandler.java +++ b/src/main/java/com/jsh/erp/exception/GlobalExceptionHandler.java @@ -3,11 +3,14 @@ import com.alibaba.fastjson.JSONObject; import com.jsh.erp.constants.ExceptionConstants; import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestControllerAdvice; import javax.servlet.http.HttpServletRequest; +import java.util.List; +import java.util.stream.Collectors; @Slf4j @RestControllerAdvice @@ -32,6 +35,19 @@ return status; } + // 这里针对校验org.springframework.web.bind.MethodArgumentNotValidException 异常的处置 + if (e instanceof MethodArgumentNotValidException) { + status.put(ExceptionConstants.GLOBAL_RETURNS_CODE, 400); + List<String> errorMessages = ((MethodArgumentNotValidException) e).getBindingResult().getFieldErrors() + .stream() + .map(fieldError -> fieldError.getField() + ": " + fieldError.getDefaultMessage()) + .collect(Collectors.toList()); + + // 以 JSON 数组形式返回 + status.put(ExceptionConstants.GLOBAL_RETURNS_MESSAGE, errorMessages); + return status; + } + status.put(ExceptionConstants.GLOBAL_RETURNS_CODE, ExceptionConstants.SERVICE_SYSTEM_ERROR_CODE); status.put(ExceptionConstants.GLOBAL_RETURNS_DATA, ExceptionConstants.SERVICE_SYSTEM_ERROR_MSG); log.error("Global Exception Occured => url : {}, msg : {}", request.getRequestURL(), e.getMessage()); -- Gitblit v1.9.3