Search in sources :

Example 1 with ErrorMessage

use of org.springframework.messaging.support.ErrorMessage in project spring-cloud-sleuth by spring-cloud.

the class TracingChannelInterceptor method beforeHandle.

/**
 * This starts a consumer span as a child of the incoming message or the current trace context.
 * It then creates a span for the handler, placing it in scope.
 */
@Override
public Message<?> beforeHandle(Message<?> message, MessageChannel channel, MessageHandler handler) {
    if (emptyMessage(message)) {
        return message;
    }
    MessageHeaderAccessor headers = mutableHeaderAccessor(message);
    TraceContextOrSamplingFlags extracted = this.extractor.extract(headers);
    // Start and finish a consumer span as we will immediately process it.
    Span consumerSpan = this.tracer.nextSpan(extracted);
    if (!consumerSpan.isNoop()) {
        consumerSpan.kind(Span.Kind.CONSUMER).start();
        consumerSpan.remoteEndpoint(Endpoint.newBuilder().serviceName(REMOTE_SERVICE_NAME).build());
        addTags(message, consumerSpan, channel);
        consumerSpan.finish();
    }
    // create and scope a span for the message processor
    this.threadLocalSpan.next(TraceContextOrSamplingFlags.create(consumerSpan.context())).name("handle").start();
    // remove any trace headers, but don't re-inject as we are synchronously processing the
    // message and can rely on scoping to access this span later.
    MessageHeaderPropagation.removeAnyTraceHeaders(headers, this.tracing.propagation().keys());
    if (log.isDebugEnabled()) {
        log.debug("Created a new span in before handle" + consumerSpan);
    }
    if (message instanceof ErrorMessage) {
        return new ErrorMessage((Throwable) message.getPayload(), headers.getMessageHeaders());
    }
    headers.setImmutable();
    return new GenericMessage<>(message.getPayload(), headers.getMessageHeaders());
}
Also used : GenericMessage(org.springframework.messaging.support.GenericMessage) MessageHeaderAccessor(org.springframework.messaging.support.MessageHeaderAccessor) ErrorMessage(org.springframework.messaging.support.ErrorMessage) TraceContextOrSamplingFlags(brave.propagation.TraceContextOrSamplingFlags) Span(brave.Span) ThreadLocalSpan(brave.propagation.ThreadLocalSpan)

Example 2 with ErrorMessage

use of org.springframework.messaging.support.ErrorMessage in project spring-integration by spring-projects.

the class MessagingGatewaySupport method doSendAndReceive.

@SuppressWarnings("unchecked")
private Object doSendAndReceive(Object object, boolean shouldConvert) {
    this.initializeIfNecessary();
    Assert.notNull(object, "request must not be null");
    MessageChannel requestChannel = getRequestChannel();
    if (requestChannel == null) {
        throw new MessagingException("No request channel available. Cannot send request message.");
    }
    registerReplyMessageCorrelatorIfNecessary();
    Object reply = null;
    Throwable error = null;
    Message<?> requestMessage = null;
    try {
        if (this.countsEnabled) {
            this.messageCount.incrementAndGet();
        }
        if (shouldConvert) {
            reply = this.messagingTemplate.convertSendAndReceive(requestChannel, object, Object.class, this.historyWritingPostProcessor);
            if (reply instanceof Throwable) {
                error = (Throwable) reply;
            }
        } else {
            requestMessage = (object instanceof Message<?>) ? (Message<?>) object : this.requestMapper.toMessage(object);
            requestMessage = this.historyWritingPostProcessor.postProcessMessage(requestMessage);
            reply = this.messagingTemplate.sendAndReceive(requestChannel, requestMessage);
            if (reply instanceof ErrorMessage) {
                error = ((ErrorMessage) reply).getPayload();
            }
        }
        if (reply == null && this.errorOnTimeout) {
            if (object instanceof Message) {
                error = new MessageTimeoutException((Message<?>) object, "No reply received within timeout");
            } else {
                error = new MessageTimeoutException("No reply received within timeout");
            }
        }
    } catch (Exception e) {
        if (logger.isDebugEnabled()) {
            logger.debug("failure occurred in gateway sendAndReceive: " + e.getMessage());
        }
        error = e;
    }
    if (error != null) {
        MessageChannel errorChannel = getErrorChannel();
        if (errorChannel != null) {
            ErrorMessage errorMessage = buildErrorMessage(requestMessage, error);
            Message<?> errorFlowReply = null;
            try {
                errorFlowReply = this.messagingTemplate.sendAndReceive(errorChannel, errorMessage);
            } catch (Exception errorFlowFailure) {
                throw new MessagingException(errorMessage, "failure occurred in error-handling flow", errorFlowFailure);
            }
            if (shouldConvert) {
                Object result = (errorFlowReply != null) ? errorFlowReply.getPayload() : null;
                if (result instanceof Throwable) {
                    this.rethrow((Throwable) result, "error flow returned Exception");
                }
                return result;
            }
            if (errorFlowReply != null && errorFlowReply.getPayload() instanceof Throwable) {
                this.rethrow((Throwable) errorFlowReply.getPayload(), "error flow returned an Error Message");
            }
            if (errorFlowReply == null && this.errorOnTimeout) {
                if (object instanceof Message) {
                    throw new MessageTimeoutException((Message<?>) object, "No reply received from error channel within timeout");
                } else {
                    throw new MessageTimeoutException("No reply received from error channel within timeout");
                }
            }
            return errorFlowReply;
        } else {
            // no errorChannel so we'll propagate
            this.rethrow(error, "gateway received checked Exception");
        }
    }
    return reply;
}
Also used : MessageChannel(org.springframework.messaging.MessageChannel) ErrorMessage(org.springframework.messaging.support.ErrorMessage) Message(org.springframework.messaging.Message) MessagingException(org.springframework.messaging.MessagingException) MessageTimeoutException(org.springframework.integration.MessageTimeoutException) ErrorMessage(org.springframework.messaging.support.ErrorMessage) MessagingException(org.springframework.messaging.MessagingException) MessageTimeoutException(org.springframework.integration.MessageTimeoutException) MessageDeliveryException(org.springframework.messaging.MessageDeliveryException) MessageMappingException(org.springframework.integration.mapping.MessageMappingException)

Example 3 with ErrorMessage

use of org.springframework.messaging.support.ErrorMessage in project spring-integration by spring-projects.

the class AdvisedMessageHandlerTests method enhancedRecoverer.

@Test
public void enhancedRecoverer() throws Exception {
    QueueChannel channel = new QueueChannel();
    ErrorMessageSendingRecoverer recoverer = new ErrorMessageSendingRecoverer(channel);
    recoverer.publish(new GenericMessage<>("foo"), new GenericMessage<>("bar"), new RuntimeException("baz"));
    Message<?> error = channel.receive(0);
    assertThat(error, instanceOf(ErrorMessage.class));
    assertThat(error.getPayload(), instanceOf(MessagingException.class));
    MessagingException payload = (MessagingException) error.getPayload();
    assertThat(payload.getCause(), instanceOf(RuntimeException.class));
    assertThat(payload.getCause().getMessage(), equalTo("baz"));
    assertThat(payload.getFailedMessage().getPayload(), equalTo("bar"));
    assertThat(((ErrorMessage) error).getOriginalMessage().getPayload(), equalTo("foo"));
}
Also used : QueueChannel(org.springframework.integration.channel.QueueChannel) MessagingException(org.springframework.messaging.MessagingException) ErrorMessage(org.springframework.messaging.support.ErrorMessage) Test(org.junit.Test)

Example 4 with ErrorMessage

use of org.springframework.messaging.support.ErrorMessage in project spring-integration by spring-projects.

the class PayloadTypeSelectorTests method testSuperclassOfAcceptedTypeIsNotSelected.

@Test
public void testSuperclassOfAcceptedTypeIsNotSelected() {
    PayloadTypeSelector selector = new PayloadTypeSelector(RuntimeException.class);
    assertFalse(selector.accept(new ErrorMessage(new Exception("test"))));
}
Also used : ErrorMessage(org.springframework.messaging.support.ErrorMessage) MessagingException(org.springframework.messaging.MessagingException) PayloadTypeSelector(org.springframework.integration.selector.PayloadTypeSelector) Test(org.junit.Test)

Example 5 with ErrorMessage

use of org.springframework.messaging.support.ErrorMessage in project spring-integration by spring-projects.

the class ErrorMessageExceptionTypeRouterTests method noMatchAndNoDefaultChannel.

@Test
public void noMatchAndNoDefaultChannel() {
    Message<?> failedMessage = new GenericMessage<String>("foo");
    IllegalArgumentException rootCause = new IllegalArgumentException("bad argument");
    RuntimeException middleCause = new RuntimeException(rootCause);
    MessageHandlingException error = new MessageHandlingException(failedMessage, "failed", middleCause);
    ErrorMessage message = new ErrorMessage(error);
    ErrorMessageExceptionTypeRouter router = new ErrorMessageExceptionTypeRouter();
    router.setBeanFactory(beanFactory);
    router.setApplicationContext(TestUtils.createTestApplicationContext());
    router.setChannelMapping(MessageDeliveryException.class.getName(), "messageDeliveryExceptionChannel");
    router.setResolutionRequired(true);
    router.setBeanName("fooRouter");
    try {
        router.handleMessage(message);
        fail("MessageDeliveryException expected");
    } catch (Exception e) {
        assertThat(e, instanceOf(MessageDeliveryException.class));
        assertThat(e.getMessage(), containsString("'fooRouter'"));
    }
}
Also used : GenericMessage(org.springframework.messaging.support.GenericMessage) MessageDeliveryException(org.springframework.messaging.MessageDeliveryException) ErrorMessage(org.springframework.messaging.support.ErrorMessage) MessageHandlingException(org.springframework.messaging.MessageHandlingException) MessageDeliveryException(org.springframework.messaging.MessageDeliveryException) MessageRejectedException(org.springframework.integration.MessageRejectedException) MessageHandlingException(org.springframework.messaging.MessageHandlingException) Test(org.junit.Test)

Aggregations

ErrorMessage (org.springframework.messaging.support.ErrorMessage)59 Test (org.junit.Test)47 CountDownLatch (java.util.concurrent.CountDownLatch)17 GenericMessage (org.springframework.messaging.support.GenericMessage)17 MessagingException (org.springframework.messaging.MessagingException)14 AtomicReference (java.util.concurrent.atomic.AtomicReference)13 Message (org.springframework.messaging.Message)12 QueueChannel (org.springframework.integration.channel.QueueChannel)11 MessageHandlingException (org.springframework.messaging.MessageHandlingException)11 Socket (java.net.Socket)9 ArrayList (java.util.ArrayList)7 LongRunningIntegrationTest (org.springframework.integration.test.support.LongRunningIntegrationTest)7 Semaphore (java.util.concurrent.Semaphore)6 Log (org.apache.commons.logging.Log)6 Matchers.containsString (org.hamcrest.Matchers.containsString)6 DirectFieldAccessor (org.springframework.beans.DirectFieldAccessor)6 BeanFactory (org.springframework.beans.factory.BeanFactory)5 MessageDeliveryException (org.springframework.messaging.MessageDeliveryException)5 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)4 ServerSocket (java.net.ServerSocket)3