← Wiki

Invalid Message Channel in Mule: the invoice request that cannot be read is kept with its reason

  • 12 min read
On this page

Code

The invoicing service receives invoice requests as JSON. Now and then one arrives that cannot be read: a truncated body, XML instead of JSON, a negative amount, a currency with no code. Invoicing it is impossible, and discarding it erases the only proof that someone sent something wrong. The Invalid Message Channel solves this by moving the message that makes no sense to a separate channel, where someone can examine it. Mule has no component for it; the example reads the body inside a Try, checks the fields with DataWeave and stores the invalid request in an Object Store with the reason and the body as it arrived.

The problem

The invoice request for order ORD-5402 arrives with the body { "orderId": "ORD-5402", "amount": and nothing else. A flow that reads the payload as JSON fails with an expression error, and the lab’s global handler returns a generic 500. The sender does not know what went wrong, and the people who operate the service have nothing to examine.

The other bad way out is to swallow it: an on-error-continue that answers 200 and moves on. The request vanishes, and the system that sent it believes the invoice is on its way.

What is missing is a place of its own for the messages the receiver does not understand, apart from the normal flow, with the reason and the original content.

The pattern in the book

The book asks how a receiver can gracefully handle a message that makes no sense. The solution is for the receiver to move the improper message to an Invalid Message Channel, a special channel for the messages that could not be processed by their receivers (Invalid Message Channel).

The channel is not used in normal communication, so accumulating improper messages in it disturbs nothing. An error handler that wants to diagnose these messages can have a receiver on the invalid channel and examine them as they arrive.

The book places this pattern next to the Dead Letter Channel, and the difference lies in who decides. The Dead Letter Channel answers what the messaging system does with a message it cannot or should not deliver (Dead Letter Channel): the message may be perfect, and the problem is the delivery. With the Invalid Message Channel the delivery succeeded; it is the receiver that reads the message and concludes the content is no good. Trying again does not help, because a wrong message stays wrong.

The diagram redraws the book’s sketch (CC BY 4.0) in the order scenario:

Checkout sends the invoice requests to the invoice requests channel, which delivers them to the Invoicing receiver. If the request makes sense, it goes on to invoicing. If it does not make sense, the dashed line leads to the Invalid Message Channel.

In Mule

Mule has no component that is the invalid channel. Anypoint MQ has dead-letter queues, which receive undelivered messages (Configuring and Using Queues); the queues page describes nothing for invalid messages, so the consumer would have to recognize them and publish them to a queue of their own (this page’s inference). With Anypoint MQ, the invalid channel would be an ordinary queue, a Point-to-Point Channel with a consumer that examines what arrives (this page’s recommendation).

The example runs without a broker. The invalid channel is an Object Store, and the receiver is an HTTP flow that makes three checks in order: the content type, the JSON read and the required fields. The first one that fails sets the reason, and the request goes to the channel with that reason.

Deciding by content whether the message continues or not is reminiscent of the Message Filter, and the example uses a Choice for it. The difference is the destination: the filter discards what is of no interest, and the invalid channel keeps what is not understood.

The POST /eip/invoices/requests endpoint goes to the first decision, whether the Content-Type is JSON. If not, the request goes to the invalid channel, with the reason and the body. If yes, the next decision asks whether the JSON is well-formed; if not, it goes to the invalid channel. If yes, the next decision asks whether the required fields are present; if not, it goes to the invalid channel. If yes, the request is accepted, with 202. From the invalid channel, the 400 response with the id goes back to the sender.

In the MuleSoft documentation

The documentation page Enterprise Integration Patterns Using Mule does not list the Invalid Message Channel. The closest row is the Message Filter’s, which it maps to the Validation module; the invalid channel on this page is the destination of what fails validation, and the project decides that destination.

The example

The flow keeps the Content-Type and the body as text before any read, so that the invalid channel receives what arrived and not an interpreted version. Then it checks the type and reads the JSON inside a Try:

<set-variable doc:name="SET vContentType" variableName="vContentType" value="#[attributes.headers.'content-type' default '']" />
<set-variable doc:name="SET vRawBody" variableName="vRawBody" value="#[if (payload.^raw == null) '' else read(payload.^raw, 'text/plain') as String]" />
<choice doc:name="Check Content Type">
	<when expression="#[not (lower(vars.vContentType) startsWith 'application/json')]">
		<set-variable doc:name="SET vReason" variableName="vReason" value="#['unsupported content type: ' ++ (if (isEmpty(vars.vContentType)) 'none' else vars.vContentType)]" />
	</when>
	<otherwise>
		<try doc:name="Try Parse JSON">
			<set-variable doc:name="SET vRequest" variableName="vRequest" value="#[read(vars.vRawBody, 'application/json')]" />
			<error-handler>
				<on-error-continue doc:name="On Error Continue (malformed JSON)" type="MULE:EXPRESSION" logException="false">
					<set-variable doc:name="SET vReason" variableName="vReason" value="malformed JSON" />
				</on-error-continue>
			</error-handler>
		</try>
	</otherwise>
</choice>

In the repository: src/main/mule/eip/invalid-message-channel/invalid-message-channel.xml

The type is compared in lowercase because the HTTP specification says the media type and subtype tokens are case-insensitive (RFC 9110, section 8.3.1): Application/JSON is JSON. The startsWith also accepts parameters, such as ; charset=UTF-8. The read uses DataWeave’s JSON format (JSON Format), and a malformed body makes read fail with an expression error. The documentation lists EXPRESSION among the Mule errors (Mule Errors), and the Try catches only that type. The on-error-continue does not swallow the error: it turns the failure into a reason, and the flow goes on to the decision.

Well-formed JSON may still not be an invoice request. A DataWeave script lists all the violations at once instead of stopping at the first:

<ee:transform doc:name="List Field Violations">
	<ee:variables>
		<ee:set-variable variableName="vViolations"><![CDATA[%dw 2.0
output application/java
var r = vars.vRequest
---
if (!(r is Object)) ["body must be a JSON object"]
else [
	("orderId is required") if (!(r.orderId is String) or isEmpty(r.orderId)),
	("amount must be a positive number") if (!(r.amount is Number) or ((r.amount default 0) <= 0)),
	("currency must be a 3-letter code") if (!(r.currency is String) or !((r.currency default "") matches /[A-Z]{3}/))
]]]></ee:set-variable>
	</ee:variables>
</ee:transform>

In a larger contract, the Validate schema operation of the JSON module does the same check against a JSON Schema and throws JSON:SCHEMA_NOT_HONOURED when the document does not follow the schema (Validating Documents Against a JSON Schema with the JSON Module). The handling would be the same: the error becomes the reason.

With a reason set, the sub-flow stores the message in the invalid channel and only then rejects the request:

<sub-flow name="sf-send-to-invalid-message-channel" doc:description="Keeps an invalid message in the invalid message channel with its reason, content type and raw body, then rejects it with 400.">
	<set-variable doc:name="SET vInvalidMessageId" variableName="vInvalidMessageId" value="#['INV-MSG-' ++ uuid()]" />
	<os:store doc:name="Store Invalid Message" key="#[vars.vInvalidMessageId]" objectStore="eip-imc-invalid-messages-store">
		<os:value><![CDATA[#[output application/java --- { invalidMessageId: vars.vInvalidMessageId, reason: vars.vReason, contentType: vars.vContentType, body: vars.vRawBody, receivedAt: now() as String, correlationId: correlationId }]]]></os:value>
	</os:store>
	<logger doc:name="WARN: Log invalid message" level="WARN" message="#['Invoice request moved to the invalid message channel as ' ++ vars.vInvalidMessageId ++ ': ' ++ vars.vReason ++ ', correlationId=' ++ correlationId]" />
	<raise-error doc:name="Raise BAD_REQUEST Error - Invalid message" type="APP:BAD_REQUEST" description="#['Invalid message ' ++ vars.vInvalidMessageId ++ ': ' ++ vars.vReason]" />
</sub-flow>

The channel entry holds the reason, the content type, the body as it arrived, the time and the correlationId. The 400 that comes back carries the same id as the entry (INV-MSG-...), so the sender can quote that id to the people who operate the service. The sender finds out because HTTP is request and response; on a queue, the sender would not know, and the invalid channel would be the only record.

A valid request is stored and gets 202 ACCEPTED. A second valid request with the same orderId gets 409 and does not go to the invalid channel: it reads perfectly, and the problem is a business one.

Caveats

  • An invalid message that only fails may end up in the dead-letter queue. With Anypoint MQ, a consumer that lets the error propagate sends the message back to the queue. The documentation describes two separate counts: the queue’s delivery attempts before rerouting to the configured DLQ (default 10) and the connector’s maxRedeliveryCount, which throws MULE:REDELIVERY_EXHAUSTED, an error the application can handle by moving the message to a DLQ (Configuring and Using Queues). With a DLQ configured, the malformed message fails the same way on every attempt and reaches the DLQ mixed with the ones that were not delivered for another reason (an inference from the documentation). Recognizing the invalid one on the first read and publishing it to a queue of its own separates the two cases.
  • The JSON read can fail far from the Listener. In a community forum case, with DataWeave 2.0, JSON with control characters failed with Unexpected character '\u001f' when read as JSON; the fix was to receive the body as text/plain, test the read with try(() -> read(payload, "application/json")) and decide in a Choice (Handling invalid Json payloads smoothly and extracting useful data). The example does something equivalent, with the Try scope and the body kept as text before any read, and that is why it has something to store in the channel.
  • The Mule 3 JSON filter does not exist in Mule 4. In a 2019 Stack Overflow case, json:is-json-filter inside a message-filter did not reject invalid JSON, and the answer suggested validating with an empty schema or with a DataWeave transformation (How to check invalid json input in mule?). Mule 4 has no filters, and the migration documentation says to use the Validation module (Migrating Filters); the question stays the same, and the answer in Mule 4 is the explicit read inside a Try or the JSON module’s Validate schema (this page’s recommendation).
  • Comparing the Content-Type literally refuses valid messages. An == against 'application/json' sends to the invalid channel a request sent as Application/JSON; charset=UTF-8, for two reasons: the case (the RFC rule above) and the charset parameter. The channel fills up with messages that were fine (an inference from the code and the RFC; the imc-content-type-is-matched-in-any-case test covers the case).

When not to use it

When the sender is on the other side of a synchronous call and nobody is there to examine the channel, a 400 with the reason is enough: the client fixes it and sends again, and storing the message only accumulates data (the example uses HTTP because the lab has no broker; on a queue, the channel would be the only record). When the failure is one of delivery or of a system that is down, the destination is the Dead Letter Channel or the redelivery of Guaranteed Delivery, not the invalid channel: the message is right and may pass on a new attempt. And the channel keeps the body as it arrived; if it carries personal data, the channel needs the same protection and the same retention as the main system (this page’s recommendations).

Running the example and the tests

git clone https://github.com/brunosouzas/mulesoft-patterns-examples.git
cd mulesoft-patterns-examples
mvn clean test

The project needs Java 17, Maven 3.9+ and the Mule 4.9 runtime. MUnit runs on the Enterprise runtime, so Maven needs access to MuleSoft’s Enterprise repository (credentials in ~/.m2/settings.xml).

The suite invalid-message-channel-test-suite.xml pins the behavior, observed on Mule 4.9.17 with MUnit 3.7.1:

Test What it proves
imc-valid-request-is-processed A valid request gets 202 ACCEPTED, is stored, and the invalid channel stays empty
imc-malformed-json-goes-to-the-invalid-channel A body that is not valid JSON gets 400 with the invalid message’s id and enters the channel with the reason and the body as it arrived
imc-schema-violation-goes-to-the-invalid-channel Well-formed JSON with no orderId, a negative amount and an invalid currency gets 400 and enters the channel with the reason schema violation: orderId is required; amount must be a positive number; currency must be a 3-letter code
imc-wrong-content-type-goes-to-the-invalid-channel An XML body is not read as a request and enters the channel as an unsupported content type
imc-json-array-goes-to-the-invalid-channel A JSON array reads fine but is not a request, and enters the channel
imc-content-type-is-matched-in-any-case A valid request sent as Application/JSON; charset=UTF-8 gets 202 and does not go to the channel
imc-repeated-order-id-is-refused A valid request with an already accepted orderId gets 409, the first one is kept, and nothing goes to the channel

The malformed JSON test checks the response, the channel entry and the request that was not stored:

<munit:validation>
	<munit-tools:assert-that doc:name="400" expression="#[vars.vPosted.status]" is="#[MunitTools::equalTo(400)]" />
	<munit-tools:assert-that doc:name="JSON" expression="#[vars.vPosted.contentType]" is="#[MunitTools::startsWith('application/json')]" />
	<munit-tools:assert-that doc:name="Names it" expression="#[vars.vPosted.body.error]" is="#[MunitTools::startsWith('Invalid message INV-MSG-')]" />
	<munit-tools:assert-that doc:name="Says why" expression="#[vars.vPosted.body.error]" is="#[MunitTools::endsWith(': malformed JSON')]" />
	<munit-tools:assert-that doc:name="One invalid message" expression="#[sizeOf(vars.vInvalid.body)]" is="#[MunitTools::equalTo(1)]" />
	<munit-tools:assert-that doc:name="Reason" expression="#[vars.vInvalid.body[0].reason]" is="#[MunitTools::equalTo('malformed JSON')]" />
	<munit-tools:assert-that doc:name="Body kept" expression="#[vars.vInvalid.body[0].body]" is="#[MunitTools::equalTo('{ &quot;orderId&quot;: &quot;ORD-IMC-2&quot;, &quot;amount&quot;: ')]" />
	<munit-tools:assert-that doc:name="Same id as the 400" expression="#[vars.vPosted.body.error]" is="#[MunitTools::containsString(vars.vInvalid.body[0].invalidMessageId)]" />
	<munit-tools:assert-that doc:name="Not processed" expression="#[vars.vGet.status]" is="#[MunitTools::equalTo(404)]" />
</munit:validation>

In the repository: src/test/munit/eip/invalid-message-channel-test-suite.xml

To call the endpoints, run the application in Anypoint Studio (port 8081) and use the Invalid Message Channel entries in requests.http:

### EIP invalid message channel — a valid request, a malformed one, then the channel
POST {{base}}/eip/invoices/requests
Content-Type: application/json

{ "orderId": "ORD-5401", "amount": 99.9, "currency": "BRL" }

###
POST {{base}}/eip/invoices/requests
Content-Type: application/json

{ "orderId": "ORD-5402", "amount":

###
GET {{base}}/eip/invoices/invalid-messages

In the repository: requests.http

The first POST gets 202, the second gets 400 with the invalid message’s id, and the GET on the channel shows only the second, with the reason malformed JSON and the truncated body as it was sent. The other patterns are in the catalog of integration patterns in Mule and, by component name, in the index by component.

Code for this page