baseurl = \ruoyi-ui\src
前端
\views\system\user
1.
line 31
<el-form-item label="用户名称" prop="userName">
<el-input
v-model="queryParams.userName"
placeholder="请输入用户名称"
clearable
size="small"
style="width: 240px"
@keyup.enter.native="handleQuery"
/>
</el-form-item>
2.
line 145
<el-table-column label="用户名称" align="center" key="userName" prop="userName" v-if="columns[1].visible" :show-overflow-tooltip="true" />
3.
line 241
<el-form-item v-if="form.userId == undefined" label="用户名称" prop="userName">
<el-input v-model="form.userName" placeholder="请输入用户名称" maxlength="30" />
</el-form-item>
4.
line 426
columns: [
{ key: 0, label: `用户编号`, visible: true },
{ key: 1, label: `用户名称`, visible: true },
{ key: 2, label: `用户昵称`, visible: true },
{ key: 3, label: `部门`, visible: true },
{ key: 4, label: `手机号码`, visible: true },
{ key: 5, label: `状态`, visible: true },
{ key: 6, label: `创建时间`, visible: true }
],
// 表单校验
// rules: {
// userName: [
// { required: true, message: "用户名称不能为空", trigger: "blur" },
// { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
5.
line 617
/** 提交按钮 */
submitForm: function() {
this.$refs["form"].validate(valid => {
if (valid) {
if (this.form.userId != undefined) {
updateUser(this.form).then(response => {
this.$modal.msgSuccess("修改成功");
this.open = false;
this.getList();
});
} else {
addUser(this.form).then(response => {
this.$modal.msgSuccess("新增成功");
this.open = false;
this.getList();
});
}
}
});
},
/api/system/user
6.
// 修改用户
export function updateUser(data) {
return request({
url: '/system/user',
method: 'put',
data: data
})
}
7.
<el-form-item label="用户昵称" prop="nickName">
<el-input v-model="form.nickName" placeholder="请输入用户昵称" /> // 删除了限制条件maxlength=30
</el-form-item>
INPUT
xuhwenfmriyuxhg87g8e7wyfgx8w7e len=30 无法继续输入但是没报错
IMAGE
搞半天开了两个RUOYI 。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
IMAGE
表单校验全部失效
触发异常
输入:“nxy7n2rgf3gtft789wgtfdtgxtgd2789y3xgd789tj3gxcw3j7jtgd87cgtwx3c8t732gwcxty7gn2e8wrfg7你干嘛哎呦 ”
后端输出
21:22:38.608 [http-nio-8080-exec-30] ERROR c.r.f.w.e.GlobalExceptionHandler - [handleMethodArgumentNotValidException,101] - Validation failed for argument [0] in public com.ruoyi.common.core.domain.AjaxResult com.ruoyi.web.controller.system.SysUserController.add(com.ruoyi.common.core.domain.entity.SysUser) with 2 errors: [Field error in object ‘sysUser’ on field ‘nickName’: rejected value [nxy7n2rgf3gtft789wgtfdtgxtgd2789y3xgd789tj3gxcw3j7jtgd87cgtwx3c8t732gwcxty7gn2e8wrfg7你干嘛哎呦]; codes [Size.sysUser.nickName,Size.nickName,Size.java.lang.String,Size]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [sysUser.nickName,nickName]; arguments []; default message [nickName],30,0]; default message [用户昵称长度不能超过30个字符]] [Field error in object ‘sysUser’ on field ‘userName’: rejected value [null]; codes [NotBlank.sysUser.userName,NotBlank.userName,NotBlank.java.lang.String,NotBlank]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [sysUser.userName,userName]; arguments []; default message [userName]]; default message [用户账号不能为空]]
前端输出
request.js:75 Uncaught (in promise) Error: 用户账号不能为空
Uncaught (in promise) Error: 用户昵称长度不能超过30个字符
这是怎么回事呢?
后端进行异常的数据处理
/**
* 用户信息
*
* @author ruoyi
*/
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController
{
@Autowired
private ISysUserService userService;
@Autowired
private ISysRoleService roleService;
@Autowired
private ISysPostService postService;
@PostMapping
public AjaxResult add(@Validated @RequestBody SysUser user)
{
if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName())))
{
return AjaxResult.error("新增用户'" + user.getUserName() + "'失败,登录账号已存在");
}
else if (StringUtils.isNotEmpty(user.getPhonenumber())
&& UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
{
return AjaxResult.error("新增用户'" + user.getUserName() + "'失败,手机号码已存在");
}
else if (StringUtils.isNotEmpty(user.getEmail())
&& UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
{
return AjaxResult.error("新增用户'" + user.getUserName() + "'失败,邮箱账号已存在");
}
user.setCreateBy(getUsername());
user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
return toAjax(userService.insertUser(user));
}
@Validated注解告诉系统需要进行验证
package org.springframework.validation.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Validated {
Class<?>[] value() default {};
}
具体的验证标准依赖以下注解
@NotBlank 非空
@Size 对长度限制 此处为 < 30
@NotBlank(message = "用户账号不能为空")
@Size(min = 0, max = 30, message = "用户账号长度不能超过30个字符")
public String getUserName()
{
return userName;
}
@Size(min = 0, max = 30, message = "用户昵称长度不能超过30个字符")
public String getNickName()
{
return nickName;
}
不符合条件就抛出异常 code = 500
public class MethodArgumentNotValidException extends BindException {
private final MethodParameter parameter;
public MethodArgumentNotValidException(MethodParameter parameter, BindingResult bindingResult) {
super(bindingResult);
this.parameter = parameter;
}
public final MethodParameter getParameter() {
return this.parameter;
}
public String getMessage() {
StringBuilder sb = (new StringBuilder("Validation failed for argument [")).append(this.parameter.getParameterIndex()).append("] in ").append(this.parameter.getExecutable().toGenericString());
BindingResult bindingResult = this.getBindingResult();
if (bindingResult.getErrorCount() > 1) {
sb.append(" with ").append(bindingResult.getErrorCount()).append(" errors");
}
sb.append(": ");
Iterator var3 = bindingResult.getAllErrors().iterator();
while(var3.hasNext()) {
ObjectError error = (ObjectError)var3.next();
sb.append('[').append(error).append("] ");
}
return sb.toString();
}
}
回到前端
响应处理函数 处理异常的第一道入口
else if (code === 500) {
Message({
message: msg,
type: 'error'
})
return Promise.reject(new Error(msg))
}
然后就看到了如上的报错
自定义异常处理注解参数
// @Size(min = 0, max = 30, message = "用户昵称长度不能超过30个字符")
@Size(min = 30, max = 60, message = "用户昵称长度必须介于30-60个字符之间")
修改完之后进行测试
输入:“1”
后端报错:
21:48:28.860 [http-nio-8080-exec-4] ERROR c.r.f.w.e.GlobalExceptionHandler - [handleMethodArgumentNotValidException,101] - Validation failed for argument [0] in public com.ruoyi.common.core.domain.AjaxResult com.ruoyi.web.controller.system.SysUserController.add(com.ruoyi.common.core.domain.entity.SysUser): [Field error in object ‘sysUser’ on field ‘nickName’: rejected value [1]; codes [Size.sysUser.nickName,Size.nickName,Size.java.lang.String,Size]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [sysUser.nickName,nickName]; arguments []; default message [nickName],60,30]; default message [用户昵称长度必须介于30-60个字符之间]]
org.springframework.web.bind.MethodArgumentNotValidException: Validation failed for argument [0] in public com.ruoyi.common.core.domain.AjaxResult com.ruoyi.web.controller.system.SysUserController.add(com.ruoyi.common.core.domain.entity.SysUser): [Field error in object ‘sysUser’ on field ‘nickName’: rejected value [1]; codes [Size.sysUser.nickName,Size.nickName,Size.java.lang.String,Size]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [sysUser.nickName,nickName]; arguments []; default message [nickName],60,30]; default message [用户昵称长度必须介于30-60个字符之间]]
前端报错:
Uncaught (in promise) Error: 用户昵称长度必须介于30-60个字符之间
at _default
不得不说SPRING DOCKER 等大厂的日志系统遥遥领先
以上