From 1ebbf5431cec198fe6aec00b2de74398dfedf33f Mon Sep 17 00:00:00 2001 From: pikaqiudeshujia Date: Sat, 11 May 2024 16:07:19 +0800 Subject: [PATCH] =?UTF-8?q?release-=20=E6=B7=BB=E5=8A=A0=E6=A0=A1=E9=AA=8C?= =?UTF-8?q?=E6=8A=A5=E9=94=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AbstractBaseExceptionHandler.java | 49 ++++++++++++++----- 1 file changed, 38 insertions(+), 11 deletions(-) diff --git a/luoo_common/src/main/java/controller/AbstractBaseExceptionHandler.java b/luoo_common/src/main/java/controller/AbstractBaseExceptionHandler.java index 02aec9a..e1a9f22 100644 --- a/luoo_common/src/main/java/controller/AbstractBaseExceptionHandler.java +++ b/luoo_common/src/main/java/controller/AbstractBaseExceptionHandler.java @@ -1,24 +1,51 @@ package controller; -import java.util.Arrays; -import java.util.Map; -import java.util.Map.Entry; -import java.util.stream.Collectors; - -import javax.servlet.http.HttpServletRequest; - -import org.springframework.util.CollectionUtils; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.ResponseBody; - import api.Result; import api.StatusCode; import dto.UserLoginDto; import exception.BizException; import lombok.extern.slf4j.Slf4j; +import org.springframework.util.CollectionUtils; +import org.springframework.validation.BindingResult; +import org.springframework.validation.ObjectError; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseBody; + +import javax.servlet.http.HttpServletRequest; +import java.util.Arrays; +import java.util.Map; +import java.util.Map.Entry; +import java.util.StringJoiner; +import java.util.stream.Collectors; @Slf4j public abstract class AbstractBaseExceptionHandler extends BaseController { + /** + * 参数校检异常 + * + * @param e 实体类校验 + */ + @ExceptionHandler(value = MethodArgumentNotValidException.class) + @ResponseBody + public Result handle(MethodArgumentNotValidException e) { + BindingResult bindingResult = e.getBindingResult(); + + StringJoiner joiner = new StringJoiner(";"); + + for (ObjectError error : bindingResult.getAllErrors()) { + String code = error.getCode(); + String[] codes = error.getCodes(); + + String property = codes[1]; + property = property.replace(code, "").replaceFirst(".", ""); + + String defaultMessage = error.getDefaultMessage(); + joiner.add(property + defaultMessage); + } + return Result.failed(StatusCode.MUSIC_COMMON_FAILED, joiner.toString()); + } + @ExceptionHandler(value = Exception.class) @ResponseBody public Result error(Exception e, HttpServletRequest request) {