Hibernate 错误日志中会显示不同的异常名称
我的Hibernate对象需要在保存之前手动分配ID。但我忘了分配它,因此出现了以下错误日志:Hibernate 错误日志中会显示不同的异常名称,hibernate,exception-handling,Hibernate,Exception Handling,我的Hibernate对象需要在保存之前手动分配ID。但我忘了分配它,因此出现了以下错误日志: ERROR errors.GrailsExceptionResolver - IdentifierGenerationException occurred when processing request: [POST] /hrims/hapum/maintenance/department/save Stacktrace follows: Message: ids for this class mu
ERROR errors.GrailsExceptionResolver - IdentifierGenerationException occurred when processing request: [POST] /hrims/hapum/maintenance/department/save
Stacktrace follows:
Message: ids for this class must be manually assigned before calling save(): ph.gov.nhmfc.hapum.Department
Line | Method
->> 24 | save in ph.gov.nhmfc.DomainService$$EQDMPY5t
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 191 | save in ph.gov.nhmfc.hapum.DepartmentService$$EQDM563D
| 85 | save . . . . . . in ph.gov.nhmfc.hapum.maintenance.DepartmentController
| 198 | doFilter in grails.plugin.cache.web.filter.PageFragmentCachingFilter
| 63 | doFilter . . . . in grails.plugin.cache.web.filter.AbstractFilter
| 449 | executeChain in org.apache.shiro.web.servlet.AbstractShiroFilter
| 365 | call . . . . . . in org.apache.shiro.web.servlet.AbstractShiroFilter$1
| 90 | doCall in org.apache.shiro.subject.support.SubjectCallable
| 83 | call . . . . . . in ''
| 383 | execute in org.apache.shiro.subject.support.DelegatingSubject
| 362 | doFilterInternal in org.apache.shiro.web.servlet.AbstractShiroFilter
| 125 | doFilter in org.apache.shiro.web.servlet.OncePerRequestFilter
| 1145 | runWorker . . . in java.util.concurrent.ThreadPoolExecutor
| 615 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 744 | run . . . . . . in java.lang.Thread
这就是我试图捕捉标识生成异常的原因:
try {
hibernate.save(insert: true)
}
catch(IdentifierGenerationException e) {
errors.push("An identifier should be assigned for this record before saving.")
}
catch(Exception e) {
println(e.getClass())
errors.push("An error has occured.")
}
令我惊讶的是,它没有转到第一个catch
语句,而是转到第二个并打印:
class org.springframework.orm.hibernate4.HibernateSystemException
有什么好处?可以安全地假设所有的IdentifierGenerationException
将由HibernateSystemException
处理。如果在HibernateSystemException
下有其他异常
被“分类”,该怎么办
这是我的try-catch
语句,看起来像:
try {
hibernate.save(insert: true)
}
catch(IdentifierGenerationException e) {
errors.push("An identifier should be assigned for this record before saving.")
}
catch(HibernateSystemException e) {
errors.push("An identifier should be assigned for this record before saving.")
}
catch(Exception e) {
errors.push("An unidentifieable error has occured.")
}
我在Grails2.4.4上使用Hibernate 4。在您的例子中,IdentifierGenerationException
似乎是HibernateSystemException
的嵌套异常。因此,如果只想捕获没有id的对象,就不应该尝试捕获HibernateSystemException
,因为HibernateSystemException
也可能是由IdentifierGenerationException
以外的原因引起的
您应该检查异常的原因,然后检查嵌套异常是否为instanceofIdentifierGenerationException
。或者检查对象id是否为空。请将异常的完整stacktrace添加到您的帖子中。对于Spring的异常处理,必须使用DataAccessException