Série da semana: Primeiros passos no React

Veja mais

Como capturar raise exception de validação do postgresql com hibernate

18/11/2015

1

Estou em meu primeiro projeto em Java!
Estou utilizando Hibernate com JSF.
Utilizo banco postgresql, e tenho algumas triggers que disparam raises como por exemplo:

Raise Exception 'Operação não permitida!';


Não sei como fazer para capturar esse trecho do erro para mostrar na página web!

Segue detalhes do meu código:

Método no Controller
	@Transactional
	public String saveItem() {
		try {
			solitpedService.save(solitpedEdit);

			MessageHandler.placeInfoMessage("item_save_success",
					String.valueOf(solitpedEdit.getId().getNnumeroitped()));

			return callback();
		} catch (PersistEntityException e) {
			MessageHandler.placeErrorMessage("item_save_error");
			logger.error("Error on save item");
			e.printStackTrace();

			return Constants.PAGE_NULL;
		}
	}


Classe PersistEntityException
	public class PersistEntityException extends Exception {

		private static final long serialVersionUID = 6962204158729560915L;

		public PersistEntityException() { }

		public PersistEntityException(String msg) {
			super(msg);
		}

		public PersistEntityException(String error, Exception e) {
			super(error, e);
		}
	}


Método no Service
	@Override
	public Solitped save(Solitped solitped) throws PersistEntityException {
		return solitpedDAO.createNew(solitped);
	}


Método no DAO
    @Override
    public T createNew(T entityBean) throws PersistEntityException {
    	try {
    		getEntityManager().persist(entityBean);
    	} catch (EntityExistsException e) {
			throw new PersistEntityException("Entity already exists.");
		} catch (IllegalArgumentException e) {
			throw new PersistEntityException("The argument is not an entity.");
		} catch (TransactionRequiredException e) {
			throw new PersistEntityException("No Transaction active.");
		} catch (Exception e) {
			throw new PersistEntityException("Error while persisting entity.");
		}
    	return entityBean;
    }


Saída do Console
Hibernate: insert into MINHATABELA (CAMPO1, ...) values (?, ...)
Nov 18, 2015 9:04:48 AM com.sun.faces.lifecycle.InvokeApplicationPhase execute
ADVERTÊNCIA: #{solpedidController.saveItem()}: javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not execute statement
javax.faces.FacesException: #{solpedidController.saveItem()}: javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not execute statement
	at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:117)
	at javax.faces.component.UICommand.broadcast(UICommand.java:315)
	at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:791)
	at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1256)
	at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
	at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
	at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
	at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
	at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:100)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
	at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
	at org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:177)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
	at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
	at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
	at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
	at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
	at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
	at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
	at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
	at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
	at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
	at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
	at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
	at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
	at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
	at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
	at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
	at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
	at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
	at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
	at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
	at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
	at java.lang.Thread.run(Thread.java:745)
Caused by: javax.faces.el.EvaluationException: javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not execute statement
	at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
	at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:101)
	... 69 more
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not execute statement
	at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1387)
	at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1310)
	at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:277)
	at com.km.web.latim.dao.SolitpedDAOImp.findBySolpedid(SolitpedDAOImp.java:35)
	at com.km.web.latim.service.SolitpedServiceImp.findBySolpedid(SolitpedServiceImp.java:51)
	at com.km.web.latim.controller.SolpedidController.loadSolitpedList(SolpedidController.java:247)
	at com.km.web.latim.controller.SolpedidController.saveItem(SolpedidController.java:830)
	at com.km.web.latim.controller.SolpedidController$$FastClassBySpringCGLIB$$c99dc484.invoke(<generated>)
	at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
	at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:708)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
	at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
	at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
	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:644)
	at com.km.web.latim.controller.SolpedidController$$EnhancerBySpringCGLIB$$c90e093e.saveItem(<generated>)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:606)
	at org.apache.el.parser.AstValue.invoke(AstValue.java:278)
	at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:273)
	at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
	at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
	... 70 more
Caused by: org.hibernate.exception.GenericJDBCException: could not execute statement
	at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:54)
	at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
	at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
	at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:136)
	at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:58)
	at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3081)
	at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3523)
	at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:88)
	at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:393)
	at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:385)
	at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:301)
	at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:339)
	at org.hibernate.event.internal.DefaultAutoFlushEventListener.onAutoFlush(DefaultAutoFlushEventListener.java:62)
	at org.hibernate.internal.SessionImpl.autoFlushIfRequired(SessionImpl.java:1211)
	at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1268)
	at org.hibernate.internal.QueryImpl.list(QueryImpl.java:101)
	at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:268)
	... 92 more
Caused by: org.postgresql.util.PSQLException: ERRO: solerror: NÃO QUERO QUE SEJA FEITO ISSO.
	at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2102)
	at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1835)
	at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257)
	at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:500)
	at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:388)
	at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:334)
	at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeUpdate(NewProxyPreparedStatement.java:147)
	at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:133)
	... 105 more


Página XHTML
<?xml version="1.0" encoding="UTF-8"?>
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:ui="http://java.sun.com/jsf/facelets"
	xmlns:p="http://primefaces.org/ui">

	<ui:include src="../solempre/panel.xhtml"/>
	<ui:include src="breadCrumbEdit.xhtml" />

	<h:form id="manageForm" prependId="false">
		<p:messages id="messages" autoUpdate="true" closable="true" />
	
    	<p:panelGrid columns="2" columnClasses="ui-grid-col-2,ui-grid-col-10" layout="grid" styleClass="ui-panelgrid-blank">
			<p:outputLabel value="#{msg.item_product}">
				<span class="required">*</span>
			</p:outputLabel>
			<p:selectOneMenu id="itemProductId"
				converter="solproduConverter" 
				value="#{solpedidController.solproduEdit}" 
				required="true" 
				requiredMessage="#{msg.item_product_required}"
				styleClass="WidAutoOnMobile"
				effect="fade" filter="true" filterMatchMode="contains">
        		<f:selectItem itemLabel="#{msg.global_select_one}" itemValue="" noSelectionOption="true" />
        		<f:selectItems value="#{solpedidController.solproduList}" 
        			var="_solprodu" 
        			itemLabel="#{_solprodu.cnomeprodu}" 
        			itemValue="#"/>
    		</p:selectOneMenu>

			<p:outputLabel value="#{msg.item_qtd}"/>
			<p:inputText id="itemQtdId"
				value="#{solpedidController.solitpedEdit.nquatdeitped}"
				requiredMessage="#{msg.item_qtd_required}"
				styleClass="WidAutoOnMobile"/>
				
			<p:outputLabel value="#{msg.item_price}"/>
			<p:inputText id="itemPriceId"
				value="#{solpedidController.solitpedEdit.nprecoitped}"
				requiredMessage="#{msg.item_price_required}"
				styleClass="WidAutoOnMobile">
				<f:convertNumber pattern="#,##0.00"></f:convertNumber>  
			</p:inputText>

		</p:panelGrid>
		
		<p:panel>
			<p:commandButton id="save"
				icon="fa fa-save" 
				action="#{solpedidController.saveItem()}"
				value="#{msg.global_save}"
				update="manageForm" 
				ajax="true"
				rendered="#{!solpedidController.idDefinedItem()}">
				<f:param name="nnumeropedid" value="#{solpedidController.solpedidEdit.nnumeropedid}"/>
				<f:param name="tabActive" value="#{solpedidController.tabActive}"/>
	  			<p:tooltip for="save" value="#{msg.tooltip_save}" />
			</p:commandButton>

			<p:commandButton id="update"
				icon="fa fa-refresh" 
				action="#{solpedidController.updateItem()}"
				value="#{msg.global_update}"
				update="manageForm"
				ajax="true"
				rendered="#{solpedidController.idDefinedItem()}">
				<f:param name="nnumeropedid" value="#{solpedidController.solpedidEdit.nnumeropedid}"/>
				<f:param name="tabActive" value="#{solpedidController.tabActive}"/>
	  			<p:tooltip for="update" value="#{msg.tooltip_update}" />
			</p:commandButton>
			
			<p:commandButton id="cancel"
				value="#{msg.global_cancel}" 
				icon="fa fa-close"
				action="#{solpedidController.cancelItem()}"
				immediate="true"
				ajax="true">
				<f:param name="nnumeropedid" value="#{solpedidController.solpedidEdit.nnumeropedid}"/>
				<f:param name="tabActive" value="#{solpedidController.tabActive}"/>
	  			<p:tooltip for="cancel" value="#{msg.tooltip_cancel}" />
			</p:commandButton>
		</p:panel>
	</h:form>
</ui:composition>



Preciso que esse trecho do erro:
solerror: NÃO QUERO QUE SEJA FEITO ISSO.


Seja exibido em meu p:message:
<p:messages id="messages" autoUpdate="true" closable="true" />


Alguma sugestão?
Responder