|
@@ -0,0 +1,60 @@
|
|
|
+package com.charging.chargingparking.utils;
|
|
|
+
|
|
|
+import java.util.Set;
|
|
|
+
|
|
|
+import javax.validation.ConstraintViolation;
|
|
|
+import javax.validation.ConstraintViolationException;
|
|
|
+
|
|
|
+import org.slf4j.Logger;
|
|
|
+import org.slf4j.LoggerFactory;
|
|
|
+import org.springframework.validation.BindException;
|
|
|
+import org.springframework.validation.BindingResult;
|
|
|
+import org.springframework.validation.FieldError;
|
|
|
+import org.springframework.web.HttpRequestMethodNotSupportedException;
|
|
|
+import org.springframework.web.bind.annotation.ExceptionHandler;
|
|
|
+import org.springframework.web.bind.annotation.RestControllerAdvice;
|
|
|
+
|
|
|
+@RestControllerAdvice
|
|
|
+public class RequestValidateExceptionHandler {
|
|
|
+
|
|
|
+ private static final Logger logger=LoggerFactory.getLogger(RequestValidateExceptionHandler.class);
|
|
|
+
|
|
|
+ //处理请求参数格式错误 @RequestParam上validate失败后抛出的异常是javax.validation.ConstraintViolationException
|
|
|
+ @ExceptionHandler(ConstraintViolationException.class)
|
|
|
+ public RespVO constraintViolationExceptionHandler(ConstraintViolationException e) {
|
|
|
+ //e.printStackTrace();
|
|
|
+ Set<ConstraintViolation<?>> constraintViolations=e.getConstraintViolations();
|
|
|
+ StringBuilder error=new StringBuilder();
|
|
|
+ for(ConstraintViolation<?> itm : constraintViolations) {
|
|
|
+ //System.out.println(itm.getInvalidValue()+":"+itm.getPropertyPath()+":"+itm.getMessage());
|
|
|
+ error.append(itm.getMessage()+";");
|
|
|
+ }
|
|
|
+ //jdk8 写法:String message = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining());
|
|
|
+ return RespVOBuilder.error(error.toString());//
|
|
|
+ }
|
|
|
+
|
|
|
+ @ExceptionHandler(BindException.class)
|
|
|
+ public RespVO validationExceptionHandler(BindException e) {
|
|
|
+ //e.printStackTrace();
|
|
|
+ BindingResult bindingResult = e.getBindingResult();
|
|
|
+ StringBuilder error=new StringBuilder();
|
|
|
+ for (FieldError fieldError : bindingResult.getFieldErrors()) {
|
|
|
+ error.append(fieldError.getDefaultMessage()+";");
|
|
|
+ }
|
|
|
+ return RespVOBuilder.error(error.toString());
|
|
|
+ }
|
|
|
+
|
|
|
+ @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
|
|
|
+ public RespVO methodUnsupportExceptionHandler(HttpRequestMethodNotSupportedException e) {
|
|
|
+ logger.error("不支持该请求方式",e);
|
|
|
+ return RespVOBuilder.error("不支持该请求方式");
|
|
|
+
|
|
|
+ }
|
|
|
+
|
|
|
+ @ExceptionHandler(Exception.class)
|
|
|
+ public RespVO otherExceptionHandler(Exception e) {
|
|
|
+ logger.error("服务出错",e);
|
|
|
+ return RespVOBuilder.error("服务出错");
|
|
|
+
|
|
|
+ }
|
|
|
+}
|