DataAccessException
DataAccessException是Mybatis封裝的異常,繼承了RuntimeException這個類。
步驟
- Mapper接口拋出DataAccessException異常
int insertSelective(BusArea record) throws DataAccessException;
- ServiceImpl拋出DataAccessException異常
@Override
public boolean insertSelective(BusArea busArea) throws DataAccessException {
boolean result = this.busAreaMapper.insertSelective(busArea) > 0;
return result;
}
- Controller捕獲異常,在捕獲DataAccessException之前可以捕獲其他runtime異常。
@RequestMapping("insertSelective")
@ResponseBody
public Map insertSelective(BusArea area) {
String uuid = UUIDGenerator.getUUID();
area.setId(uuid);
Map resultmap = new HashMap();
String code = "fail";
String msg = "添加失敗!";
try {
boolean rb = this.busAreaService.insertSelective(area);
if (rb){
code = "success";
msg = "添加成功!";
}
}catch (DuplicateKeyException e){
msg = "該區域名稱已存在,請勿重復添加!";
}catch (DataAccessException e){
msg = "添加出現異常!";
}
resultmap.put("code",code);
resultmap.put("msg",msg);
return resultmap;
}