异常捕获真实情况案例分析:
首先场景是这样的,有一个表比如是用户表,用户表的用户名字段加上了唯一索引,防止在并发情况下出现多个用户名为同样的,在业务层执行插入时候我们进行异常捕获,捕获底层抛出唯一索引的错误
代码:
try {
int insert = baseMapper.insert(userBean);
if (insert == 0) {
return "插入失败";
}
}catch (Exception ee) {
ee.printStackTrace();
}
异常打印信息:
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '1213' for key 'username'
这里我们看到MySQLIntegrityConstraintViolationException这个异常类,我们把这个类进行catch试下,结果提示
说不会在try块中进行抛出,也就捕获不了,下面是解决方案:
由于spring框架有帮我们做底层异常的处理封装,这时候我们不知道到底哪个类用来catch,这是非常蛋疼的问题!!!!
去看spring文档,了解下spring的异常处理类到底有哪些?不不不不!不能这样!!!
这时候我们用反射来解决:
用到了getClass和getName
getClass:获取运行类
getName:获取当前类的路径
try {
int insert = baseMapper.insert(userBean);
if (insert == 0) {
return "插入失败";
}
} catch (Exception ee) {
String name = ee.getClass().getName();
System.out.println(name);
}
我们再一次测试,控制台打印:
org.springframework.dao.DuplicateKeyException
嗯,这就是spring在底层抛出的真实类,我们用这个类进行catch
try {
int insert = baseMapper.insert(userBean);
if (insert == 0) {
return "插入失败";
}
}catch (DuplicateKeyException ee) {
return "插入失败。。。已经有了这个用户";
}
这个方法就能轻松的帮我们找出抛出异常到底是哪个“家伙”了,进行相应的处理!