În Mule 4, error handling se reduce la trei decizii: ce tipuri de eroare prinzi (tipurile conectorilor, precum HTTP:CONNECTIVITY și DB:CONNECTIVITY, sau tipurile tale APP: ridicate cu raise-error), dacă handler-ul propagă eroarea sau continuă, și unde stă handler-ul (un scope try, flow-ul sau un error handler global implicit). Ghidul acoperă fiecare decizie, apoi retry-urile cu until-successful, un circuit breaker construit pe Object Store și un dead letter queue.
Petru Constantin este MuleSoft Certified Developer Level 2 (2025) și construiește API-uri MuleSoft pentru integrare enterprise din 2022. Exemplele de cod sunt scrise pe documentația Mule 4.9 LTS și HTTP Connector 1.12.
Concepte fundamentale de gestionare a erorilor
Să înțelegem modelul de erori al MuleSoft:
<!-- Try scope with typed handlers; the listener returns the status set in vars.httpStatus -->
<flow name="basic-error-handling-flow">
<http:listener config-ref="HTTP_Listener_config" path="/orders" method="POST">
<http:response statusCode="#[vars.httpStatus default 201]"/>
</http:listener>
<try doc:name="Try Block">
<!-- Main processing logic -->
<db:insert config-ref="Database_Config" doc:name="Insert Order">
<db:sql>INSERT INTO orders (customer_id, total) VALUES (:customerId, :total)</db:sql>
<db:input-parameters><![CDATA[#[{
customerId: payload.customerId,
total: payload.total
}]]]></db:input-parameters>
</db:insert>
<http:request
method="POST"
config-ref="Inventory_HTTP_Config"
path="/reserve"
doc:name="Reserve Inventory"/>
<error-handler>
<!-- on-error-continue: the flow completes and the listener sends this payload -->
<on-error-continue type="DB:CONNECTIVITY" doc:name="DB Connection Error">
<logger level="ERROR" message="Database connection failed: #[error.description]"/>
<ee:transform doc:name="DB Error Response">
<ee:message>
<ee:set-payload><![CDATA[%dw 2.0
output application/json
---
{
errorCode: "DB_CONNECTION_ERROR",
message: "Database temporarily unavailable",
retryAfter: 30,
correlationId: correlationId
}]]></ee:set-payload>
</ee:message>
<ee:variables>
<ee:set-variable variableName="httpStatus">503</ee:set-variable>
</ee:variables>
</ee:transform>
</on-error-continue>
<!-- Handle HTTP request errors -->
<on-error-continue type="HTTP:CONNECTIVITY, HTTP:TIMEOUT" doc:name="HTTP Error">
<logger level="ERROR" message="External service error: #[error.description]"/>
<ee:transform doc:name="Service Error Response">
<ee:message>
<ee:set-payload><![CDATA[%dw 2.0
output application/json
---
{
errorCode: "EXTERNAL_SERVICE_ERROR",
message: "Inventory service unavailable",
retryAfter: 60,
correlationId: correlationId
}]]></ee:set-payload>
</ee:message>
<ee:variables>
<ee:set-variable variableName="httpStatus">503</ee:set-variable>
</ee:variables>
</ee:transform>
</on-error-continue>
<!-- Catch-all for unexpected errors -->
<on-error-continue type="ANY" doc:name="Generic Error">
<logger level="ERROR" message="Unexpected error: #[error.errorType] - #[error.description]"/>
<ee:transform doc:name="Generic Error Response">
<ee:message>
<ee:set-payload><![CDATA[%dw 2.0
output application/json
---
{
errorCode: "INTERNAL_ERROR",
message: "An unexpected error occurred",
correlationId: correlationId
}]]></ee:set-payload>
</ee:message>
<ee:variables>
<ee:set-variable variableName="httpStatus">500</ee:set-variable>
</ee:variables>
</ee:transform>
</on-error-continue>
</error-handler>
</try>
</flow>Tipuri de erori personalizate
Definește și aruncă tipuri de erori personalizate:
<!-- Custom APP: error types are declared by raising them; no separate file is needed -->
<flow name="custom-error-types-flow">
<http:listener config-ref="HTTP_Listener_config" path="/customers/{customerId}" method="GET">
<!-- on-error-propagate ends in an error response: send the handler's payload and status -->
<http:error-response statusCode="#[vars.httpStatus default 500]">
<http:body><![CDATA[#[payload]]]></http:body>
</http:error-response>
</http:listener>
<set-variable variableName="customerId" value="#[attributes.uriParams.customerId]" doc:name="Store Customer ID"/>
<!-- Validate customer ID format -->
<choice doc:name="Validate Customer ID">
<when expression="#[vars.customerId matches /^CUST-\d{6}$/]">
<logger level="DEBUG" message="Valid customer ID format"/>
</when>
<otherwise>
<raise-error type="APP:INVALID_CUSTOMER_ID"
description="Customer ID must be in format CUST-XXXXXX"/>
</otherwise>
</choice>
<!-- Query customer -->
<db:select config-ref="Database_Config" doc:name="Get Customer">
<db:sql>SELECT * FROM customers WHERE customer_id = :customerId</db:sql>
<db:input-parameters><![CDATA[#[{
customerId: vars.customerId
}]]]></db:input-parameters>
</db:select>
<!-- Check if customer exists -->
<choice doc:name="Check Customer Exists">
<when expression="#[sizeOf(payload) > 0]">
<ee:transform doc:name="Transform Customer">
<ee:message>
<ee:set-payload><![CDATA[%dw 2.0
output application/json
---
{
customerId: payload[0].customer_id,
name: payload[0].name,
email: payload[0].email,
status: payload[0].status
}]]></ee:set-payload>
</ee:message>
</ee:transform>
</when>
<otherwise>
<raise-error type="APP:CUSTOMER_NOT_FOUND"
description="#['Customer not found: ' ++ vars.customerId]"/>
</otherwise>
</choice>
<!-- Check customer status -->
<choice doc:name="Check Customer Status">
<when expression="#[payload.status == 'ACTIVE']">
<logger level="DEBUG" message="Customer is active"/>
</when>
<when expression="#[payload.status == 'SUSPENDED']">
<raise-error type="APP:CUSTOMER_SUSPENDED"
description="Customer account is suspended"/>
</when>
<when expression="#[payload.status == 'CLOSED']">
<raise-error type="APP:CUSTOMER_CLOSED"
description="Customer account is closed"/>
</when>
</choice>
<error-handler>
<on-error-propagate type="APP:INVALID_CUSTOMER_ID">
<ee:transform>
<ee:message>
<ee:set-payload><![CDATA[%dw 2.0
output application/json
---
{
error: "INVALID_CUSTOMER_ID",
message: error.description
}]]></ee:set-payload>
</ee:message>
<ee:variables>
<ee:set-variable variableName="httpStatus">400</ee:set-variable>
</ee:variables>
</ee:transform>
</on-error-propagate>
<on-error-propagate type="APP:CUSTOMER_NOT_FOUND">
<ee:transform>
<ee:message>
<ee:set-payload><![CDATA[%dw 2.0
output application/json
---
{
error: "CUSTOMER_NOT_FOUND",
message: error.description
}]]></ee:set-payload>
</ee:message>
<ee:variables>
<ee:set-variable variableName="httpStatus">404</ee:set-variable>
</ee:variables>
</ee:transform>
</on-error-propagate>
<on-error-propagate type="APP:CUSTOMER_SUSPENDED, APP:CUSTOMER_CLOSED">
<ee:transform>
<ee:message>
<ee:set-payload><![CDATA[%dw 2.0
output application/json
---
{
error: error.errorType.identifier,
message: error.description
}]]></ee:set-payload>
</ee:message>
<ee:variables>
<ee:set-variable variableName="httpStatus">403</ee:set-variable>
</ee:variables>
</ee:transform>
</on-error-propagate>
</error-handler>
</flow>Handler global de erori
Centralizează gestionarea erorilor în întreaga aplicație:
<!-- global-error-handler.xml -->
<configuration-properties file="error-config.yaml"/>
<!-- Make Global_Error_Handler the default for every flow without its own handler -->
<configuration doc:name="Configuration" defaultErrorHandler-ref="Global_Error_Handler"/>
<!-- Flows that rely on it should use an http:error-response with
statusCode="#[vars.httpStatus default 500]" and body #[payload] -->
<error-handler name="Global_Error_Handler">
<!-- APIkit router errors -->
<on-error-propagate type="APIKIT:BAD_REQUEST">
<set-variable variableName="httpStatus" value="#[400]"/>
<set-variable variableName="errorCode" value="BAD_REQUEST"/>
<flow-ref name="build-error-response"/>
</on-error-propagate>
<on-error-propagate type="APIKIT:NOT_FOUND">
<set-variable variableName="httpStatus" value="#[404]"/>
<set-variable variableName="errorCode" value="NOT_FOUND"/>
<flow-ref name="build-error-response"/>
</on-error-propagate>
<on-error-propagate type="APIKIT:METHOD_NOT_ALLOWED">
<set-variable variableName="httpStatus" value="#[405]"/>
<set-variable variableName="errorCode" value="METHOD_NOT_ALLOWED"/>
<flow-ref name="build-error-response"/>
</on-error-propagate>
<!-- A downstream API rejected our credentials: not the caller's fault -->
<on-error-propagate type="HTTP:UNAUTHORIZED, HTTP:FORBIDDEN">
<set-variable variableName="httpStatus" value="#[502]"/>
<set-variable variableName="errorCode" value="UPSTREAM_AUTH_ERROR"/>
<flow-ref name="build-error-response"/>
</on-error-propagate>
<!-- Connectivity errors (retryable) -->
<on-error-propagate type="HTTP:CONNECTIVITY, HTTP:SERVICE_UNAVAILABLE, DB:CONNECTIVITY">
<set-variable variableName="httpStatus" value="#[503]"/>
<set-variable variableName="errorCode" value="SERVICE_UNAVAILABLE"/>
<flow-ref name="build-error-response"/>
</on-error-propagate>
<!-- Timeout errors -->
<on-error-propagate type="HTTP:TIMEOUT">
<set-variable variableName="httpStatus" value="#[504]"/>
<set-variable variableName="errorCode" value="TIMEOUT"/>
<flow-ref name="build-error-response"/>
</on-error-propagate>
<!-- Application-specific errors: list each APP type you raise -->
<on-error-propagate type="APP:CUSTOMER_NOT_FOUND">
<set-variable variableName="httpStatus" value="#[404]"/>
<set-variable variableName="errorCode" value="CUSTOMER_NOT_FOUND"/>
<flow-ref name="build-error-response"/>
</on-error-propagate>
<!-- Catch-all for unexpected errors -->
<on-error-propagate type="ANY">
<set-variable variableName="httpStatus" value="#[500]"/>
<set-variable variableName="errorCode" value="INTERNAL_SERVER_ERROR"/>
<flow-ref name="build-error-response"/>
</on-error-propagate>
</error-handler>
<!-- One builder for every error response -->
<sub-flow name="build-error-response">
<ee:transform doc:name="Error Response">
<ee:message>
<ee:set-payload><![CDATA[%dw 2.0
output application/json
---
{
apiVersion: p('api.version'),
error: {
code: vars.errorCode,
// Don't expose internal error details in production
details: if (p('app.environment') != "prod") error.description else null,
timestamp: now() as String {format: "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"},
correlationId: correlationId
}
}]]></ee:set-payload>
</ee:message>
</ee:transform>
<flow-ref name="log-and-track-error"/>
</sub-flow>
<sub-flow name="log-and-track-error">
<!-- Log error details -->
<logger level="ERROR" doc:name="Log Error"
message="#[output application/json --- {correlationId: correlationId, errorType: error.errorType.identifier, errorDescription: error.description, httpStatus: vars.httpStatus}]"/>
<!-- Send to an error tracking endpoint without blocking the response -->
<async doc:name="Async Error Tracking">
<http:request
method="POST"
config-ref="Error_Tracking_HTTP_Config"
path="/api/errors"
doc:name="Send to Error Tracker">
<http:body><![CDATA[#[output application/json
---
{
application: p('app.name'),
environment: p('app.environment'),
correlationId: correlationId,
errorType: error.errorType.identifier,
errorMessage: error.description,
timestamp: now(),
severity: vars.httpStatus match {
case 500 -> "CRITICAL"
case 503 -> "HIGH"
else -> "MEDIUM"
}
}]]]></http:body>
</http:request>
</async>
</sub-flow>Strategii de retry
Implementează mecanisme inteligente de retry:
<flow name="retry-strategies-flow">
<http:listener config-ref="HTTP_Listener_config" path="/process" method="POST">
<http:error-response statusCode="#[vars.httpStatus default 500]">
<http:body><![CDATA[#[payload]]]></http:body>
</http:error-response>
</http:listener>
<!-- Retry the call; maxRetries and millisBetweenRetries accept numbers, placeholders or expressions.
millisBetweenRetries defaults to 60000 if you leave it out. -->
<until-successful
maxRetries="${retry.maxAttempts}"
millisBetweenRetries="${retry.intervalMs}"
doc:name="Retry External Call">
<http:request
method="POST"
config-ref="External_Service_Config"
path="/api/process"
doc:name="Call External Service">
<http:response-validator>
<http:success-status-code-validator values="200..299"/>
</http:response-validator>
</http:request>
</until-successful>
<error-handler>
<!-- until-successful raises MULE:RETRY_EXHAUSTED after the last failed attempt -->
<on-error-propagate type="MULE:RETRY_EXHAUSTED">
<logger level="ERROR" message="All retries exhausted: #[error.description]"/>
<ee:transform doc:name="Service Unavailable Response">
<ee:message>
<ee:set-payload><![CDATA[%dw 2.0
output application/json
---
{
errorCode: "SERVICE_UNAVAILABLE",
message: "Service unavailable after all retries",
correlationId: correlationId
}]]></ee:set-payload>
</ee:message>
<ee:variables>
<ee:set-variable variableName="httpStatus">503</ee:set-variable>
</ee:variables>
</ee:transform>
</on-error-propagate>
</error-handler>
</flow>Pattern-ul circuit breaker
Implementează circuit breaker pentru toleranța la erori:
<!-- Circuit breaker state kept in Object Store; entries expire after 300 seconds -->
<os:object-store
name="Circuit_Breaker_Store"
persistent="true"
entryTtl="300"
entryTtlUnit="SECONDS"/>
<flow name="circuit-breaker-flow">
<http:listener config-ref="HTTP_Listener_config" path="/protected/call" method="POST">
<http:error-response statusCode="#[vars.httpStatus default 500]">
<http:body><![CDATA[#[payload]]]></http:body>
</http:error-response>
</http:listener>
<!-- Check circuit state -->
<flow-ref name="check-circuit-state" doc:name="Check Circuit"/>
<choice doc:name="Circuit State Router">
<when expression="#[vars.circuitState == 'OPEN']">
<!-- Circuit is open - fail fast -->
<raise-error type="APP:CIRCUIT_OPEN"
description="Circuit breaker is OPEN. Service temporarily unavailable."/>
</when>
<otherwise>
<!-- CLOSED or HALF_OPEN: let the call through and track the result -->
<flow-ref name="execute-with-circuit-tracking" doc:name="Tracked Call"/>
</otherwise>
</choice>
<error-handler>
<on-error-propagate type="APP:CIRCUIT_OPEN">
<ee:transform>
<ee:message>
<ee:set-payload><![CDATA[%dw 2.0
output application/json
---
{
error: "SERVICE_UNAVAILABLE",
message: "Service is temporarily unavailable. Please retry later.",
retryAfter: 60
}]]></ee:set-payload>
</ee:message>
<ee:variables>
<ee:set-variable variableName="httpStatus">503</ee:set-variable>
</ee:variables>
</ee:transform>
</on-error-propagate>
</error-handler>
</flow>
<sub-flow name="check-circuit-state">
<os:retrieve
key="circuit:failure_count"
objectStore="Circuit_Breaker_Store"
target="failureCount"
doc:name="Get Failure Count">
<os:default-value><![CDATA[#[0]]]></os:default-value>
</os:retrieve>
<os:retrieve
key="circuit:last_failure_time"
objectStore="Circuit_Breaker_Store"
target="lastFailureTime"
doc:name="Get Last Failure Time">
<os:default-value><![CDATA[#[0]]]></os:default-value>
</os:retrieve>
<ee:transform doc:name="Determine Circuit State">
<ee:variables>
<ee:set-variable variableName="circuitState"><![CDATA[%dw 2.0
output application/java
var failureThreshold = 5
var resetTimeoutMs = 60000
var nowMs = now() as Number {unit: "milliseconds"}
var timeSinceLastFailure = nowMs - (vars.lastFailureTime as Number)
---
if (vars.failureCount >= failureThreshold)
if (timeSinceLastFailure > resetTimeoutMs)
"HALF_OPEN"
else
"OPEN"
else
"CLOSED"]]></ee:set-variable>
</ee:variables>
</ee:transform>
<logger level="DEBUG" message="Circuit state: #[vars.circuitState], Failures: #[vars.failureCount]"/>
</sub-flow>
<sub-flow name="execute-with-circuit-tracking">
<try doc:name="Track Circuit Status">
<http:request
method="POST"
config-ref="Protected_Service_Config"
path="/api/endpoint"
doc:name="Call Protected Service">
<http:response-validator>
<http:success-status-code-validator values="200..299"/>
</http:response-validator>
</http:request>
<!-- Success - reset failure count -->
<os:store
key="circuit:failure_count"
objectStore="Circuit_Breaker_Store"
doc:name="Reset Failure Count">
<os:value><![CDATA[#[0]]]></os:value>
</os:store>
<error-handler>
<on-error-propagate type="HTTP:CONNECTIVITY, HTTP:TIMEOUT, HTTP:SERVICE_UNAVAILABLE">
<!-- Increment failure count -->
<os:retrieve
key="circuit:failure_count"
objectStore="Circuit_Breaker_Store"
target="currentFailures"
doc:name="Get Current Failures">
<os:default-value><![CDATA[#[0]]]></os:default-value>
</os:retrieve>
<os:store
key="circuit:failure_count"
objectStore="Circuit_Breaker_Store"
doc:name="Increment Failures">
<os:value><![CDATA[#[vars.currentFailures + 1]]]></os:value>
</os:store>
<os:store
key="circuit:last_failure_time"
objectStore="Circuit_Breaker_Store"
doc:name="Update Last Failure Time">
<os:value><![CDATA[#[now() as Number {unit: "milliseconds"}]]]></os:value>
</os:store>
<logger level="WARN"
message="Circuit failure recorded. Count: #[vars.currentFailures + 1]"/>
</on-error-propagate>
</error-handler>
</try>
</sub-flow>Pattern-ul Dead Letter Queue
Gestionează mesajele eșuate în mod controlat:
<flow name="message-processing-with-dlq">
<jms:listener config-ref="JMS_Config" destination="orders.queue" doc:name="Listen for Orders"/>
<set-variable variableName="originalPayload" value="#[payload]" doc:name="Store Original"/>
<try doc:name="Process Message">
<!-- Validate message -->
<flow-ref name="validate-order-message" doc:name="Validate"/>
<!-- Process order -->
<flow-ref name="process-order" doc:name="Process"/>
<error-handler>
<!-- Transient errors: let the flow fail. The JMS listener only ACKs on success,
so the broker redelivers the message (set a redelivery limit on the broker) -->
<on-error-propagate type="HTTP:CONNECTIVITY, DB:CONNECTIVITY">
<logger level="WARN" message="Transient error, message will be redelivered: #[error.description]"/>
</on-error-propagate>
<!-- Permanent failures: park the message on the DLQ and complete the flow -->
<on-error-continue type="ANY">
<logger level="ERROR" message="Permanent failure, sending to DLQ: #[error.description]"/>
<ee:transform doc:name="Build DLQ Message">
<ee:message>
<ee:set-payload><![CDATA[%dw 2.0
output application/json
---
{
originalMessage: vars.originalPayload,
error: {
type: error.errorType.identifier,
description: error.description,
timestamp: now()
},
metadata: {
correlationId: correlationId,
source: "orders.queue",
processedAt: now()
}
}]]></ee:set-payload>
</ee:message>
</ee:transform>
<jms:publish config-ref="JMS_Config" destination="orders.dlq" doc:name="Send to DLQ"/>
<!-- Alert on DLQ -->
<async doc:name="Alert Team">
<http:request
method="POST"
config-ref="Slack_Webhook_Config"
path="/services/webhook"
doc:name="Slack Alert">
<http:body><![CDATA[#[output application/json
---
{
text: "Message sent to DLQ",
attachments: [{
color: "danger",
fields: [
{title: "Correlation ID", value: correlationId, short: true},
{title: "Error", value: error.description, short: false}
]
}]
}]]]></http:body>
</http:request>
</async>
</on-error-continue>
</error-handler>
</try>
</flow>Greșeli frecvente
- Eroare ridicată în namespace-ul unui conector. Referința
raise-errorspune că nu poți folosi namespace-uri existente ale conectorilor sau modulelor, pentru că acestea au namespace-urile lor definite. Folosești un namespace propriu, de exempluAPP:CUSTOMER_NOT_FOUND. - Așteptarea ca payload-ul din handler să ajungă în răspunsul HTTP după On Error Propagate. Fără
http:error-response, listener-ul trimite 500 cu descrierea erorii ca body. SetezistatusCodeși body-ul pehttp:error-responsesau folosești On Error Continue șihttp:response. - Tipuri de eroare cu wildcard. Referința On Error definește
typeca listă de tipuri de eroare Mule separate prin virgulă și arată doar tipuri explicite plusANY. Listezi fiecare tip pe care îl tratezi. - Intervalul implicit al
until-successfuluitat.millisBetweenRetriesare implicit 60000 ms, iar când ultima încercare eșuează scope-ul ridicăMULE:RETRY_EXHAUSTED. Scope-ul nu are o setare de exponential backoff. - Un handler global pe care nu-l folosește niciun flow. Un
error-handlercu nume devine implicit doar când îl referi dindefaultErrorHandler-refpe elementulconfiguration.
Concluzie
Gestionarea eficientă a erorilor în MuleSoft necesită o abordare pe mai multe niveluri: handlere specifice pentru erorile cunoscute, handlere globale pentru consistență, strategii de retry pentru erorile tranzitorii și circuit breaker pentru protecția sistemului. Implementează logging și alerte comprehensive pentru a menține vizibilitatea. Aceste pattern-uri asigură că integrările tale rămân reziliente și ușor de întreținut în producție.
Surse oficiale
- Mule Errors
- Raise Error Component
- Until Successful Scope
- HTTP Listener Reference
- Error Handlers
- Listening For New Messages
Pe același subiect: Ghid MuleSoft Anypoint MQ: cozi, FIFO, DLQ și moduri de ACK, MuleSoft API-Led Connectivity: ghid arhitectura, Pipeline CI/CD MuleSoft cu Maven si GitHub Actions. Mai multe articole în categoria MuleSoft, iar munca de inginerie din spatele lor e pe pagina de servicii.
Ai nevoie de un sistem AI construit și pus în producție, cu obiectivele stabilite în scris și garanția de livrare? Vezi prețul și garanția unui Sprint DeviDevs →