mybatis不鼓励捕捉异常,但在某些特定场景下需要捕捉,这个时候通过try catch是捕捉不到的,mybatis有自己的处理方式,它把异常映射成了DataAccessException,那么我们需要抛出异常并捕捉
下面是一个可行的实现方法:
在mapper对需要捕捉异常接口抛出DataAccessException:
package com.xxx.mybatis.persistence;
import org.springframework.dao.DataAccessException;
import com.xxx.mybatis.domain.Member;
public interface MemberMapper {
void insertMember(Member member) throws DataAccessException;
Member getMemberByEmail(String email);
}
然后在service也抛出异常:
public void insertMember(Member member) throws DataAccessException
{
memberMapper.insertMember(member);
}
在controller里边捕捉异常并getcause处理:
try {
memberService.insertMember(member);
} catch (DataAccessException e) {
final Throwable cause = e.getCause();
if( cause instanceof MySQLIntegrityConstraintViolationException )
{
registerResponse.setDescription("duplicate email");
registerResponse.setReturncode(601);
return registerResponse;
}
}
package com.xxx.mybatis.persistence;
import org.springframework.dao.DataAccessException;
import com.xxx.mybatis.domain.Member;
public interface MemberMapper {
void insertMember(Member member) throws DataAccessException;
Member getMemberByEmail(String email);
}
然后在service也抛出异常:
public void insertMember(Member member) throws DataAccessException
{
memberMapper.insertMember(member);
}
在controller里边捕捉异常并getcause处理:
try {
memberService.insertMember(member);
} catch (DataAccessException e) {
final Throwable cause = e.getCause();
if( cause instanceof MySQLIntegrityConstraintViolationException )
{
registerResponse.setDescription("duplicate email");
registerResponse.setReturncode(601);
return registerResponse;
}
}