2017-03-09 73 views
0

我的Hibernate对象需要在保存前手动分配ID。但我忘了给它分配所以这个错误日志中出现:错误日志中显示不同的异常名称

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 

所以这就是为什么我试图抓住IdentifierGenerationException:而不是去第一catch声明

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.") 
} 

在我惊讶的是,它然后去了第二个,并打印:

class org.springframework.orm.hibernate4.HibernateSystemException 

什么给?假设所有IdentifierGenerationException将由HibernateSystemException处理是安全的。如果还有其他Exception“分类”根据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.") 
} 

我对Grails的2.4.4使用Hibernate 4。

+0

请在您的文章中添加异常的完整堆栈跟踪。对于Spring的异常处理,你必须使用'DataAccessException' – Chaitanya

回答

0

在你的情况,似乎IdentifierGenerationExceptionHibernateSystemException的嵌套异常。因此,如果您只想捕获没有ID的对象,则不应尝试捕获HibernateSystemException,因为HibernateSystemException也可能由IdentifierGenerationException以外的其他因素引起。

您应该检查异常的原因,然后检查嵌套异常是否为exampleof IdentifierGenerationException。或者检查对象ID是否为空。