Spring Data Mongo,为什么异常不是DuplicateKeyException的实例?

时间:2019-06-25 15:24:18

标签: spring-boot spring-data-mongodb

我正在研究Spring Boot Rest MongoDB示例。在此示例中,我有Student集合,其中emailId是唯一字段(我在unique=true处应用了索引)。当某人创建新学生并使用Mongo中已经存在的emailId时,我应该得到DuplicateKeyException。但是以某种方式,对象不是DuplicateKeyException的一部分。为什么不选择DuplicateKeyException实例?

try {
    studentRepository.save(student);
} catch (Exception ex) {
    if(ex instanceof DuplicateKeyException) {
        throw new DuplicateResourceFoundException("studentName already present");
    }
    throw new DuplicateResourceFoundException("studentName already present");


    //throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, env.getProperty("error.db.exception"), ex);
} 

1 个答案:

答案 0 :(得分:0)

我能够解决这个问题。我犯了一个简单的错误,应该从org.springframework.dao.DuplicateKeyException导入。现在可以正常工作了。