在Java中,在try catch id中没有处理Exception,在try块中有一个if else

时间:2017-08-18 05:39:45

标签: java spring hibernate spring-mvc exception-handling

我是Hibernate和Springs的新手,现在我正在开发一个项目,我无法理解为什么这个try catch块无效。

项目结构如下: JSP>控制器>服务>道

我有一个名为卖家的Bean,其中包含必要的字段,并将其传递给卖方控制器,以便在数据库中进行更新,如下所示:

@RequestMapping(value = "/updateSeller")
public String updateSellerProfile(Model model, HttpSession session, SellerFormBean seller) {

    int action = seller.getAction();
    try {

        if (action == 1 || action == 2) {

                //this modify seller Profile is giving an Exception of DataIntegrityViolationException: not-null property references a null or transient value  
                seller = sellerService.modifySellerProfile(seller);


                model.addAttribute("countries", commonService.getCountryDropdown());    
            }
        if (action == 3 || action == 4) {
            sellerService.modifyCaseStudies(seller.getSellerId(), seller.getCaseStudies());
        }



        Integer sellerId = (Integer) session.getAttribute("entityId");

        SellerFormBean bean=null;
         bean = sellerService.retrieveSeller(sellerId);

        Long userId = (Long) session.getAttribute("userId");

        try {
            UserFormBean user = userService.getUser(userId);
            bean.setUser(user);
        } catch (IllegalAccessException | InvocationTargetException e) {
            log.error("sellerController - updateSeller , getUser Failed ",e);
        }



        model.addAttribute("seller", bean);
        model.addAttribute("message", "Profile updated successfully");

    }catch(IllegalStateException e){
        log.error("sellerController - updateSeller : ",e);
    } catch (NullPointerException |HibernateException e) {
        log.error("sellerController - updateSeller",e);
        model.addAttribute("error",
                "Error occured while updating the profile. Please try again later. If the problem persist, then please conctact system administrator");
    }catch(Exception e) {
        log.error("sellerController - updateSeller",e);
        model.addAttribute("error",
                "Error occured while updating the profile. Please try again later. If the problem persist, then please conctact system administrator");
    }

    return selectTab(action);
}

现在我知道错误是在哪里以及如何纠正该错误,但问题是当方法modifySellerProfile中出现异常时,异常未在控制器的try cath块中捕获。可能是什么原因?

但是当我在控制器中使用这样的东西时,会处理异常:

         try {
                //this modify seller Profile is giving an Exception of DataIntegrityViolationException: not-null property references a null or transient value  
                seller = sellerService.modifySellerProfile(seller);
            }catch (Exception e) {
                log.error("Hello My Error I caught you",e);
            }

modifySellerProfile如下:

 public void modifySellerProfile(Seller instance){
    log.debug("attaching dirty Seller instance");

     Seller sellerDo = new Seller();
    BeanUtils.copyProperties(formBean, sellerDo, "caseStudies", "references", "accelerators");
      ///====Deliberately created an exception for testing
        instance.setCompanyType(null);

        sessionFactory.getCurrentSession().saveOrUpdate(instance);

        log.debug("attach successful");

}

STACK TRACE:

<code>[http-bio-8080-exec-7] DEBUG org.springframework.orm.hibernate4.HibernateTransactionManager - Exposing Hibernate transaction as JDBC transaction [com.mysql.jdbc.JDBC4Connection@fa47468]
[http-bio-8080-exec-7] DEBUG com.htss.market.dao.SellerHome - attaching dirty Seller instance

[http-bio-8080-exec-7] DEBUG com.htss.market.dao.SellerHome - attach successful
[http-bio-8080-exec-7] DEBUG com.htss.market.dao.UserHome - getting User instance with id: 72
Hibernate: select user0_.user_id as user_id1_21_0_, user0_.first_name as first_na2_21_0_, user0_.middle_name as middle_n3_21_0_, user0_.last_name as last_nam4_21_0_, user0_.title as title5_21_0_, user0_.photo as photo6_21_0_, user0_.phone_no as phone_no7_21_0_, user0_.email_id as email_id8_21_0_, user0_.country as country9_21_0_, user0_.password as passwor10_21_0_, user0_.created_by as created11_21_0_, user0_.created_on as created12_21_0_, user0_.updated_by as updated13_21_0_, user0_.updated_on as updated14_21_0_, user0_.last_login as last_lo15_21_0_, user0_.active as active16_21_0_, user0_.country_code as country17_21_0_ from user user0_ where user0_.user_id=?
[http-bio-8080-exec-7] DEBUG com.htss.market.dao.UserHome - get successful, instance found
[http-bio-8080-exec-7] DEBUG com.htss.market.dao.UserHome - attaching clean User instance
[http-bio-8080-exec-7] DEBUG com.htss.market.dao.UserHome - attach successful



[http-bio-8080-exec-7] DEBUG org.springframework.orm.hibernate4.HibernateTransactionManager - Initiating transaction commit
[http-bio-8080-exec-7] DEBUG org.springframework.orm.hibernate4.HibernateTransactionManager - Committing Hibernate transaction on Session [SessionImpl(PersistenceContext[entityKeys=[EntityKey[com.htss.market.dao.Seller#37], EntityKey[com.htss.market.dao.User#72]],collectionKeys=[CollectionKey[com.htss.market.dao.User.userOtps#72], CollectionKey[com.htss.market.dao.User.passwordPolicies#72], CollectionKey[com.htss.market.dao.User.userEntityMappings#72]]];ActionQueue[insertions=org.hibernate.engine.spi.ExecutableList@8d70e98 updates=org.hibernate.engine.spi.ExecutableList@d6e1acb deletions=org.hibernate.engine.spi.ExecutableList@7e36f2ca orphanRemovals=org.hibernate.engine.spi.ExecutableList@4e5a4433 collectionCreations=org.hibernate.engine.spi.ExecutableList@7ec930ae collectionRemovals=org.hibernate.engine.spi.ExecutableList@38cd5fe collectionUpdates=org.hibernate.engine.spi.ExecutableList@4ae5d7e7 collectionQueuedOps=org.hibernate.engine.spi.ExecutableList@56826954 unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])]
[http-bio-8080-exec-7] DEBUG org.springframework.orm.hibernate4.HibernateTransactionManager - Initiating transaction rollback after commit exception
org.springframework.dao.DataIntegrityViolationException: not-null property references a null or transient value : com.htss.market.dao.Seller.companyType; nested exception is org.hibernate.PropertyValueException: not-null property references a null or transient value : com.htss.market.dao.Seller.companyType
    at org.springframework.orm.hibernate4.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:182)
    at org.springframework.orm.hibernate4.HibernateTransactionManager.convertHibernateAccessException(HibernateTransactionManager.java:683)
    at org.springframework.orm.hibernate4.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:565)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:757)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:726)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:478)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:272)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
    at com.htss.service.SellerService$$EnhancerBySpringCGLIB$$d68f2f19.modifySellerProfile(<generated>)
    at com.htss.web.controller.SellerController.updateSellerProfile(SellerController.java:230)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.sitemesh.webapp.contentfilter.ContentBufferingFilter.bufferAndPostProcess(ContentBufferingFilter.java:169)
    at org.sitemesh.webapp.contentfilter.ContentBufferingFilter.doFilter(ContentBufferingFilter.java:126)
    at org.sitemesh.webapp.SiteMeshFilter.doFilter(SiteMeshFilter.java:120)
    at org.sitemesh.config.ConfigurableSiteMeshFilter.doFilter(ConfigurableSiteMeshFilter.java:163)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:316)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:126)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:122)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:168)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:48)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:205)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:120)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:91)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:53)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:213)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:176)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.hibernate.PropertyValueException: not-null property references a null or transient value : com.htss.market.dao.Seller.companyType
    at org.hibernate.engine.internal.Nullability.checkNullability(Nullability.java:106)
    at org.hibernate.event.internal.DefaultFlushEntityEventListener.scheduleUpdate(DefaultFlushEntityEventListener.java:309)
    at org.hibernate.event.internal.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:160)
    at org.hibernate.event.internal.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:231)
    at org.hibernate.event.internal.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:102)
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:55)
    at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1222)
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:425)
    at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
    at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:177)
    at org.springframework.orm.hibernate4.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:557)
    ... 83 more  </code>

1 个答案:

答案 0 :(得分:0)

尝试检查Dao图层中的DataIntegrityViolationException。因为它会被捕获或Hibernate将处理/抛出它。所以它永远不会回到你的服务层。 这是因为SessionFactoryUtils

中的这部分代码
if (ex instanceof PropertyValueException) {
        return new DataIntegrityViolationException(ex.getMessage(), ex);
    }

做类似的事情:

try {
  //Some code
} catch(DataIntegrityViolationException e) {
    log.error("Data Integrity Violation Exception "+e);
}