唯一索引异常捕获

唯一索引异常捕获
强烈推介IDEA2020.2破解激活,IntelliJ IDEA 注册码,2020.2 IDEA 激活码
  • SQL执行异常类型 
java.lang.Exception
|-- java.sql.SQLException
	|-- SQLNonTransientException
		|-- SQLIntegrityConstraintViolationException
  • 示例: 
//新增机型
		try{
			aircraftService.save(aircraft);
			return R.ok(aircraft.getId());
		}catch (Exception e){
			Throwable cause = e.getCause();
			if(cause instanceof java.sql.SQLIntegrityConstraintViolationException){
				//错误信息
				String errMsg =    ((java.sql.SQLIntegrityConstraintViolationException)cause).getMessage();
				//根据约束名称定位是那个字段
				if(StringUtils.isNotBlank(errMsg) && errMsg.indexOf("ux_aircraft_model") != -1) {
					return R.failed().setMsg("机型("+aircraft.getAircraftModel()+")重复");
				}else{
					return R.failed().setMsg("新增机型失败");
				}
			}else{
				return R.failed().setMsg("新增机型失败");
			}
		}

 

本文来源huayang183,由架构君转载发布,观点不代表Java架构师必看的立场,转载请标明来源出处:https://javajgs.com/archives/18414

发表评论