2017-08-18 17 views
0

私はHibernateとSpringには新しく、今ではプロジェクトを開発していたので、なぜこのcatchブロックを試しても理解できませんワーキング。次のようにJavaで例外がtry catchのIDで処理されないtryブロックにif elseがあります

プロジェクト構造は次のとおりです。 JSP>コントローラ>サービス>ダオ

私は次のようにデータベースの更新を行うための売り手コントローラに渡されることで必要なフィールド、とビーンという名前の売り手を持っています。

@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 { 
       //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"); 

} 

スタックトレース:

<code>[http-bio-8080-exec-7] DEBUG org.springframework.orm.hibernate4.HibernateTransactionManager - Exposing Hibernate transaction as JDBC transaction [[email protected]] 
[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[[email protected] [email protected] [email protected] [email protected] [email protected]30ae [email protected]fe [email protected]e7 [email protected]6954 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> 
+0

消滅しない、それはしようと '最も近くでキャッチされますスタックトレース – Jens

+0

に例外を追加してください:SessionFactoryUtils

if (ex instanceof PropertyValueException) { return new DataIntegrityViolationException(ex.getMessage(), ex); } 

のコードのこの部分のような何かを行うため です'それが' catch 'または' throw 'で再び定義されているかどうかを管理します。あなたは 'catch(Exception e)'を持っているので、すべての例外を捕捉しますが、 'Error'は捕捉しません。スタックトレースを追加して確認します。 – AxelH

+0

'Throwable'は実際の基本クラスであり、チェックされた' Exception'からのものです。 'DataIntegrityViolationException'は例外を拡張していないかもしれませんが、別のブランチであるRuntimeExceptionをいくつか拡張しているかもしれません。ええ、少し矛盾した名前です。 Throwableをキャッチしてみてください。 –

答えて

0

を入れてみてくださいDao層のDataIntegrityViolationExceptionのチェック。それがそこに捕まえられるか、またはHibernateが処理/投げますので。だからあなたのサービス層に戻ることはありません。

try { 
    //Some code 
} catch(DataIntegrityViolationException e) { 
    log.error("Data Integrity Violation Exception "+e); 
} 
関連する問題