首先在java的log中找到引发错误所抛出的Exception
###Error updating database. java.sql.SQLInterityConstrainViolationException :
Duplicate entry 'zhangsan' for key 'employee.idx_username'
需要分析的点有两个
SQLInterityConstrainViolationException
提取出这里的exception类型
'zhangsan'
同时提取出这里的id后续用来说明这个id已经重复
@ExceptionHandler
public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
//Duplicate entry 'zhangsan' for key 'employee.idx_username'
String message = ex.getMessage();
if(message.contains("Duplicate entry")){
String[] split = message.split(" ");
String username = split[2];
String msg = username + MessageConstant.ALREADY_EXISTS;
return Result.error(msg);
}else{
return Result.error(MessageConstant.UNKNOWN_ERROR);
}
用Exception类型和 contains函数进行匹配说明确实是该错误
之后用split函数提取出username
最后拼装出msg 用Result封装返回给前端
前端看到的就是
error'zhangsan'用户名已经存在