Răsfoiți Sursa

配置管理

lenovodn 2 ani în urmă
părinte
comite
f1b8a178ab

+ 26 - 0
jeecg-boot-base-core/src/main/java/org/jeecg/common/exception/JeecgBootExceptionHandler.java

@@ -9,15 +9,23 @@ import org.springframework.dao.DataIntegrityViolationException;
 import org.springframework.dao.DuplicateKeyException;
 import org.springframework.data.redis.connection.PoolException;
 import org.springframework.http.HttpStatus;
+import org.springframework.validation.BindingResult;
+import org.springframework.validation.FieldError;
 import org.springframework.web.HttpRequestMethodNotSupportedException;
+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.ResponseStatus;
 import org.springframework.web.bind.annotation.RestControllerAdvice;
+import org.springframework.web.context.request.RequestContextHolder;
+import org.springframework.web.context.request.ServletRequestAttributes;
 import org.springframework.web.multipart.MaxUploadSizeExceededException;
 import org.springframework.web.servlet.NoHandlerFoundException;
 
 import lombok.extern.slf4j.Slf4j;
 
+import javax.servlet.http.HttpServletRequest;
+
 /**
  * 异常处理器
  * 
@@ -37,6 +45,24 @@ public class JeecgBootExceptionHandler {
 		return Result.error(e.getMessage());
 	}
 
+
+	@ResponseStatus(HttpStatus.OK)
+	@ExceptionHandler(MethodArgumentNotValidException.class)
+	@ResponseBody
+	public Result<?> exceptionHandler(MethodArgumentNotValidException ex) {
+		//获取Servlet容器
+		BindingResult bindingResult = ex.getBindingResult();
+		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
+		//获取request请求
+		HttpServletRequest request = attributes.getRequest();
+		StringBuilder sb = new StringBuilder("校验失败:");
+		for (FieldError fieldError : bindingResult.getFieldErrors()) {
+			sb.append(fieldError.getField()).append(":").append(fieldError.getDefaultMessage()).append(", ");
+		}
+		String msg = sb.toString();
+		return Result.error(msg);
+	}
+
 	/**
 	 * 处理自定义微服务异常
 	 */