DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Introducing Stalactite ORM
  • Spring Boot: JUnit Integration Test
  • Spring Reactive Microservices: A Showcase
  • Frequently Used Annotations in Spring Boot Applications

Trending

  • Apache Spark 4.0: Transforming Big Data Analytics to the Next Level
  • How GitHub Copilot Helps You Write More Secure Code
  • Security by Design: Building Full-Stack Applications With DevSecOps
  • Tired of Spring Overhead? Try Dropwizard for Your Next Java Microservice
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. Spring Integration Error Handling with Router, ErrorChannel, and Transformer

Spring Integration Error Handling with Router, ErrorChannel, and Transformer

This article explains how errors are handled when using the messaging system with Spring Integration and how to handle route and redirect to specific channel.

By 
Upender Chinthala user avatar
Upender Chinthala
·
Oct. 31, 14 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
47.5K Views

Join the DZone community and get the full member experience.

Join For Free

This article explains how errors are handled when using the messaging system with Spring Integration and how to handle route and redirect to specific channel.

High Level Diagram


spring-mockrunner.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:c="http://www.springframework.org/schema/c"
xmlns:context="http://www.springframework.org/schema/context"
default-autowire="default"
xmlns:jms="http://www.springframework.org/schema/jms"
xsi:schemaLocation="http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.1.xsd
http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.1.xsd">


  <bean id="destinationManager" class="com.mockrunner.jms.DestinationManager"/>

      <bean id="inBoundQueue" factory-bean="destinationManager" factory-method="createQueue">
      <constructor-arg index="0" value="MOCKRUNNER-IN-QUEUE" />
      </bean>

      <bean id="configurationManager" class="com.mockrunner.jms.ConfigurationManager"/>

      <bean id="jmsQueueConnectionFactory" class="com.mockrunner.mock.jms.MockQueueConnectionFactory">
      <constructor-arg index="0" ref="destinationManager" />
      <constructor-arg index="1" ref="configurationManager" />
      </bean>

      <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
      <property name="connectionFactory" ref="jmsQueueConnectionFactory"/>
      </bean>     
</beans>

applicationContext-jms-int.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:c="http://www.springframework.org/schema/c"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:int-jms="http://www.springframework.org/schema/integration/jms"
xsi:schemaLocation="http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.1.xsd
http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/integrationhttp://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/integration/jmshttp://www.springframework.org/schema/integration/jms/spring-integration-jms.xsd
http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.1.xsd">

<import resource="spring-mockrunner.xml"/> 

      <int:poller default="true" fixed-delay="50"/>

      <int:channel id="inputChannel">
      <int:queue  capacity="5"/>
      </int:channel>

       <int:channel id="outputChannel">
       <int:queue  capacity="5"/>
      </int:channel>


<!--  chain, inbound message, convert msg to file -->    

 <int-jms:inbound-channel-adapter connection-factory="jmsQueueConnectionFactory" destination="inBoundQueue"  channel="inputChannel" >
 <int:poller fixed-rate="1000"></int:poller>
 </int-jms:inbound-channel-adapter>

  <int:transformer input-channel="inputChannel" ref="xmlMsgToCustomerPojoTransformer" output-channel="outputChannel">
  </int:transformer>

<int:payload-type-router  input-channel="outputChannel">
  <int:mapping type="org.springframework.oxm.UnmarshallingFailureException" channel="errorChannel"/>
  <int:mapping type="com.spijb.domain.Customer" channel="outputChannel" />
</int:payload-type-router>

<int:service-activator input-channel="errorChannel" ref="errorLogger" method="logError"/>

<int:service-activator input-channel="outputChannel" ref="customerActivator"  output-channel="nullChannel" method="handleCustomer"/>

<bean id="marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>com.spijb.domain.Customer</value>
</list>
</property>
</bean>

   <bean id="xmlMsgToCustomerPojoTransformer" class="com.spijb.transformers.CustomerMessageTransformer">
   <property name="unmarshaller" ref="marshaller" />
   </bean>



<bean id="customerActivator" class="com.spijb.serviceactivator.CustomerServiceActivator"/>

<bean id="errorLogger" class="com.spijb.seriveactivator.ErrorLogger" />
  </beans>

Router:  A router component can be used to distribute the messages to mul-tiple destinations. For example, the requirement is that when raise in mapping exception  should be sent to errorchannel while other scenario like if parsed xml sucessfully then it should  sent to outputchannel. The Router component will take care of this task. 

PayloadTypeRouter: The PayloadTypeRouter determines the routing of messages to different channels based on the type of the payload. The router endpoint attached to an incoming channel will evaluate the type and accordingly distribute (route) the messages to other channels expecting that particular type. The payload-type-router element is used to plug in this type of routing logic
payload-type-router to the incoming channel, the all-in-channel which receives all types of messages. Next, use the mapping attribute to set the expected type and its corresponding channel. 
All the messages whose payload type is a UnmarshallingFailureException will be sent to errorChannel , while those of the Customer type are sent to outputChannel . It is a simple categorization based on payload type.

Customer.java 

package com.spijb.domain;


import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Customer {

   String name;
   int age;
   int id;

   public String getName() {
      return name;
   }

   @XmlElement
   public void setName(String name) {
      this.name = name;
   }

   public int getAge() {
      return age;
   }

   @XmlElement
   public void setAge(int age) {
      this.age = age;
   }

   public int getId() {
      return id;
   }

   @XmlAttribute
   public void setId(int id) {
      this.id = id;
   }
   @Override
   public String toString()
   {
      return "Name "+this.name+"\n"+"Id: "+this.id+"\n"+" Age "+this.age;
   }
}

CustomerMessageTransformer.java

package com.spijb.transformers;

import java.io.IOException;
import java.io.StringReader;

import javax.xml.transform.stream.StreamSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.integration.Message;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.oxm.Unmarshaller;
import org.springframework.oxm.XmlMappingException;

import com.spijb.domain.Customer;


public class CustomerMessageTransformer {

   private static final Logger logger = LoggerFactory.getLogger(CustomerMessageTransformer.class); 
   private Unmarshaller unmarshaller;

   public void setUnmarshaller(Unmarshaller unmarshaller) {
      this.unmarshaller = unmarshaller;
   }

   @SuppressWarnings("rawtypes")
   public Message transform(String message)
   {
      logger.info("Message Received \r\n"+message);
      try {
         Customer customer = (Customer)unmarshaller.unmarshal(new StreamSource(new StringReader(message)));

         return MessageBuilder.withPayload(customer).build();
      } catch (XmlMappingException e) {
         return MessageBuilder.withPayload(e).build();
      } catch (IOException e){
         return MessageBuilder.withPayload(e).build();
        }
        catch(Exception e){
           return MessageBuilder.withPayload(e).build();
        }
   }
}

CustomerMessageTransformer: This transformer basically throw Exception when it occur and it wrap into as Message hand over to payloadtype router and then payloadtype router decides which channel has to forward this exception. In this class if any kind of unmarshal related exception such as XMLMappingException, IOException or Exception throws then it wrap it as Message return it;otherwise it return Customer object. Here you can customize or define your own exception and wrap it and return so that you have only one map type in payloadtype router.

ErrorLogger.java

package com.spijb.serviceactivator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.integration.Message;
import org.springframework.integration.MessageDeliveryException;

public class ErrorLogger {

 private static final Logger logger = LoggerFactory.getLogger(ErrorLogger.class);   
   public void logError(Message<Exception> message)
   {
      Exception msgex=message.getPayload();
      logger.error("Exception "+msgex);
   }

}

ErrrorLogger: ErrorLoagger class actually handle exceptions and log into logger.

CustomerServiceActivator.java

package com.spijb.seriveactivator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.spijb.domain.Customer;


public class CustomerServiceActivator {

   private static final Logger logger = LoggerFactory.getLogger(CustomerServiceActivator.class); 
   public void handleCustomer(Customer customer)
   {
      logger.info("Customer information received and invoke some services here....\r\n"+customer);
   }

}

CustomerServiceActivator: This class is success scenario I mean if there are no exception while doing transformer then payloadtype router route to Customer message to outputChannel then this class method handleCustomer will invoke. In this class no implementation just logging customer information.

ErrorHandlingTest.java

package com.spijb.invoker;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.mockrunner.mock.jms.MockQueue;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:applicationContext-file-jms.xml"})
public class ErrorHandlingTest {


   @Autowired
   private JmsTemplate jmsTemplate;

   @Autowired
   private MockQueue inBoundQueue;


   @Test
   public void shouldSendCustomerToWebServiceActivator() throws InterruptedException
   {

      final StringBuffer sb = new StringBuffer();
      sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>")
       .append("<customer id=\"10001\">")
       .append("<age>35</age>")
       .append("<name>Upender</name>")
       .append("</customer>");
      jmsTemplate.send(inBoundQueue,new MessageCreator() {

      @Override
      public Message createMessage(Session session) throws JMSException {
         TextMessage textMessage = session.createTextMessage();
         textMessage.setText(sb.toString());
         return textMessage;
      }
   });
      Thread.sleep(3000);
   }

   @Test
   public void shouldSendMessageErrorLogActivator() throws InterruptedException
   {

      final StringBuffer sb = new StringBuffer();
      sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>")
       .append("<customer id=\"10001\">")
       .append("<age>a3<age>")
       .append("<name>Upender</name>")
       .append("</customer>");
      jmsTemplate.send(inBoundQueue,new MessageCreator() {

      @Override
      public Message createMessage(Session session) throws JMSException {
         TextMessage textMessage = session.createTextMessage();
         textMessage.setText(sb.toString());
         return textMessage;
      }
   });
     Thread.sleep(3000);
   }
}

ErrorHandlerTest: Spring integration test class has two methods one shouldSendCustomerToWebServiceActivator method which it will send success full scenario, and other method shouldSendMessageErrorLogActivator  will send invalid xml message and it will fail while unmarshal xml to java object.


Failed Output:

12:58:51.798 [task-scheduler-4] ERROR c.spijb.seriveactivator.ErrorLogger - Exception org.springframework.integration.MessageHandlingException: org.springframework.expression.spel.SpelEvaluationException: EL1004E:(pos 8): Method call: Method handleCustomer(org.springframework.oxm.UnmarshallingFailureException) cannot be found on com.spijb.seriveactivator.CustomerServiceActivator type

Success Output:

13:00:47.245 [task-scheduler-5] INFO  c.s.t.CustomerMessageTransformer - Message Received <?xml version="1.0" encoding="UTF-8" standalone="yes"?><customer id="10001"><age>35</age><name>Upender</name></customer>
13:00:47.277 [task-scheduler-6] INFO  c.s.s.CustomerServiceActivator - Customer information received and invoke some services here....
Name Upender
Id: 10001
Age 35


Attached maven pom.xml file for all dependencies.


Spring Integration integration test Spring Framework

Opinions expressed by DZone contributors are their own.

Related

  • Introducing Stalactite ORM
  • Spring Boot: JUnit Integration Test
  • Spring Reactive Microservices: A Showcase
  • Frequently Used Annotations in Spring Boot Applications

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!