首先解决前端方面的全局方法挂载,这里阿新使用了插件的方式为vue添加了一个全局混入,后端SQL使用了全局SQL错误处理的方式进行解决
有兴趣自己写博客的小伙伴可以访问一下我的博客:从零手撸个人博客-前后端全局解决方案
前端方面
阿新选择使用Element提供的消息提示[Element消息提示][1]
没有使用过的小伙伴可以去了解一下,很简单,对于博客而言我们只使用简单的 success 和 error 通知,后续会有大量的本地存储的读写操作,因此我们将通知和读写先封装在插件里:
export default {
install(Vue){
Vue.mixin({
methods:{
localSetObject(name,data){//对象与数组数据
localStorage.setItem(name,JSON.stringify(data));
},
localGetObject(name){
return JSON.parse(localStorage.getItem(name));
},
localSet(name,data){//普通数据
localStorage.setItem(name,data);
},
localGet(name){
return localStorage.getItem(name);
},
notifyMsgErr(msg){//返回Element错误信息对象
return {
title: 'Info',
message: msg || '未知错误',
showClose: true
}
},
notifyMsgSuc(msg){//返回Element成功信息对象
return {
title: 'Info',
message: msg,
showClose: true
}
}
},
data(){
return{
userObjectName:'user'//用户对象保存的本地key
}
}
})
}
}
这只是初步的样子,后面我们会加入大量的设置,有想法的同学可以自行添加一些,如此一来我们的前端登录相关代码就会很简洁:
login(){
userLogin(this.user).then((res)=>{
let result=res.data;
if(result.code==="100"){
this.$notify.success(this.notifyMsgSuc('登录成功!欢迎你:'+this.user.username));
this.localSetObject(this.userObjectName,{id:res.data.data,username:this.user.username});
console.log(this.localGetObject(this.userObjectName));
}else this.$notify.error(this.notifyMsgErr(result.msg));
}).catch(error=>this.$notify.error(this.notifyMsgErr(error.message)))
}
后端方面
后端的SQL全局错误的处理如下:
@Slf4j
@ResponseBody
@ControllerAdvice(annotations = {RestController.class, Controller.class})
public class globalException {
/*
* 异常处理
* 全局的sql添加冲突
* @return
* */
@ExceptionHandler(SQLIntegrityConstraintViolationException.class)
public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
log.error(ex.getMessage());
if(ex.getMessage().contains("Duplicate entry")){
String t[]=ex.getMessage().split(" ");
return R.error(t[2]+"已存在");
}
return R.error("未知错误");
}
// @ExceptionHandler(notDoAdmin.class)
// public R<String> notDoAdmin(notDoAdmin n){
//
// log.error(n.getMessage());
//
// return R.error(n.getMessage());
//
// }
}
自定义的错误处理可以像下面被注释掉的代码一样,我们可以通过getMessage获取错误信息的字符串,以此判断错误类型并做出反馈,错误CODE要遵守result包下的CODE类哈,全局SQL冲突处理设置之后,我们注册用户的代码可以非常简洁
@Override
public int setByUser(User user) {//service层 返回insert新增数据的id
userMapper.insert(user);
return getByUsername(user);
}
@PostMapping//返回新建user的id
public R<Integer> registerUser(@RequestBody User user){//controller层
return R.success(userService.setByUser(user));
}
当接收到后端返回的注册信息后,前端只需判断是否成功,若成功则自动登录(记得将当前用户id与username保存在本地)
一上午就这样度过咯