@Valid @NotEmpty 数据为空返回message回前端

@Valid @NotEmpty 数据为空返回message回前端_第1张图片
当添加注解@NotEmpty的字段为空时,返回一大段异常数据。

如果想要把@NotEmpty中的message返回给前端,
@Valid @NotEmpty 数据为空返回message回前端_第2张图片
添加代码:

@ControllerAdvice
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public AjaxResponse handleValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        String message = null;
        if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            if (fieldError != null) {
                message = fieldError.getField()+fieldError.getDefaultMessage();
            }
        }
        return AjaxResponse.error(message);
    }
}

你可能感兴趣的:(java)