|
14 | 14 | import org.apache.commons.logging.LogFactory; |
15 | 15 | import org.springframework.http.HttpStatus; |
16 | 16 | import org.springframework.lang.NonNull; |
| 17 | +import org.springframework.validation.BindingResult; |
| 18 | +import org.springframework.validation.FieldError; |
| 19 | +import org.springframework.web.bind.MethodArgumentNotValidException; |
17 | 20 | import org.springframework.web.bind.annotation.ControllerAdvice; |
18 | 21 | import org.springframework.web.bind.annotation.ExceptionHandler; |
19 | 22 | import org.springframework.web.bind.annotation.ResponseStatus; |
@@ -122,6 +125,41 @@ public ModelAndView noHandlerFoundException(HttpServletRequest request, NoHandle |
122 | 125 | return getErrorModelAndView(CommonUtil.ajaxCheck(request), "error Url" + errorURL + " || " + ext.getMessage()); |
123 | 126 | } |
124 | 127 |
|
| 128 | + @ExceptionHandler(MethodArgumentNotValidException.class) |
| 129 | + public ModelAndView methodArgumentNotValidException(HttpServletRequest request, HttpServletResponse response, |
| 130 | + MethodArgumentNotValidException ext) throws IOException { |
| 131 | + |
| 132 | + if (CommonUtil.ajaxCheck(request)) { |
| 133 | + Function<MethodArgumentNotValidException, ModelAndView> func = (ex) -> { |
| 134 | + ModelAndView mv = new ModelAndView("forward:/error"); |
| 135 | + mv.addObject("errorCode", HttpStatus.BAD_REQUEST); |
| 136 | + mv.addObject("errorMsg", makeValidErrorMessage(ex.getBindingResult())); |
| 137 | + return mv; |
| 138 | + }; |
| 139 | + return func.apply(ext); |
| 140 | + } else { |
| 141 | + Function<MethodArgumentNotValidException, ModelAndView> func = (ex) -> { |
| 142 | + ModelAndView mv = new ModelAndView("forward:/" + HttpStatus.BAD_REQUEST.value()); |
| 143 | + mv.addObject("errorCode", HttpStatus.BAD_REQUEST); |
| 144 | + mv.addObject("errorMsg", makeValidErrorMessage(ex.getBindingResult())); |
| 145 | + return mv; |
| 146 | + }; |
| 147 | + return func.apply(ext); |
| 148 | + } |
| 149 | + } |
| 150 | + |
| 151 | + private String makeValidErrorMessage(BindingResult bindingResult) { |
| 152 | + StringBuilder builder = new StringBuilder(); |
| 153 | + for (FieldError fieldError : bindingResult.getFieldErrors()) { |
| 154 | + builder.append("["); |
| 155 | + // builder.append(fieldError.getField()); |
| 156 | + builder.append(fieldError.getDefaultMessage()); |
| 157 | + builder.append("]"); |
| 158 | + } |
| 159 | + |
| 160 | + return builder.toString(); |
| 161 | + } |
| 162 | + |
125 | 163 | @ExceptionHandler(Exception.class) |
126 | 164 | public ModelAndView exceptionHandler(HttpServletRequest request, Exception ext) { |
127 | 165 | log.info("defaultException"); |
|
0 commit comments