How to get HTTP Status code from Mule application - mule

I am using Anypoint Studio 6.1 and Mule 3.8.1 and have a flow that calls MongoDB. I want to see how to get the HTTP status so I can configure my exception handling. When I disconnect MongoDB and run the Mule workflow it fails as expected, but the HTTP status is returned as null when I try this expression message.inboundProperties['http.status'] and the exception message code is -1, but when I play the error through to the end of the workflow the status shows as 500 in Postman.
How can I get the HTTP status?
Thanks

message.inboundProperties['http.status'] will give the http.status code when a HTTP Request invocation is made within the flow. If the flow is trying to invoke DB, then you may need to have a catch exception strategy inside the error handling of the flow to catch the desired exception. If the exception is matched, you can set the http.status and exception payload to be sent to the client end.

If you are using APIKit Router then you can use the following code:
<apikit:mapping-exception-strategy name="apiKitGlobalExceptionMapping">
<apikit:mapping statusCode="500">
<apikit:exception value="java.lang.Exception"/>
<set-property propertyName="Content-Type" value="application/json" doc:name="Property" />
<set-payload value="{ "message": "Internal server error" }" doc:name="Set Payload" />
</apikit:mapping>
For more details you can check here

Related

How to customise an error message generated by the Anypoint API manager standard policy?

There is an API running on the CloudHub (Mule 4.4) and protected with the standard SLA Rate Limit policy.
We have a requirement to provide a custom error message body instead of the default one generated by the policy when authentication fails.
The default error body returned by the policy looks like this:
{
"error": "Invalid client id or secret"
}
When I run the application in debugger in Studio, it is intercepting the exception and I can see that the error type produced by the policy is CLIENT-ID-ENFORCEMENT:INVALID_CREDENTIALS.
This as well indicates that the exception is reaching the Mule application itself. So, it must be a way to override the default handler with the custom one.
First, I've tried adding the handler for error type to HTTP request processing flow beside the other API Kit errors. It did not intercept the error.
Then, I've defined a separate error handler for the error type and set it as a "Default Error Handler" in the global configuration.
<configuration doc:name="Configuration" doc:id="7a7e22cd-2ee7-42ee-af15-eaf2693d72d9" defaultErrorHandler-ref="apiErrorHandler" />
<error-handler name="apiErrorHandler">
<on-error-propagate enableNotifications="true" logException="true" type="CLIENT-ID-ENFORCEMENT:*">
<ee:transform xmlns:ee="http://www.mulesoft.org/schema/mule/ee/core" xsi:schemaLocation="http://www.mulesoft.org/schema/mule/ee/core http://www.mulesoft.org/schema/mule/ee/core/current/mule-ee.xsd">
<ee:message>
<ee:set-payload><![CDATA[%dw 2.0
output application/json
---
{message: "Unauthorised"}]]></ee:set-payload>
</ee:message>
</on-error-propagate>
</error-handler>
This didn't work as well.
Can you pls advise the right way to customise the error messages returned the standard SLA policy?
To be clear, I'm well aware that it is possible to code your own custom policy. But the intention is to keep the standard one and just customise the response for some error types.
This is not currently possible. Policies have to handle their own errors, they can not be intercepted in the flow.

MuleSoft AnypointStudio

I have scripts:
<set-variable value="#[attributes.headers['Authorization']]" doc:name="apikey" doc:id="69f6509e-8c0c-4832-854e-d7c07675cb49" variableName="apiKey"/>
<http:request method="GET" doc:name="Request" doc:id="86d51474-a71e-438c-bb24-59471424c4f9" config-ref="HTTP_Request_configuration">
<http:headers ><![CDATA[#[output application/java
---
{
Authorization : vars.apiKey
}]]]></http:headers>
</http:request>
and in the postman I have in Headers Key: Authorization and value the apiKey.
After call in Postman I have this message in AS:
HTTP GET on resource failed: bad request (400)
Why I have bad request?
anypThe developers using the library should be able to disable certain fields in the JSON output. The list of disabled fields should be configurable. The flows responsible for logging in the JSON structure should be able to read the configuration and should not log those fields. This feature will be required in higher environments in case the team decides to disable certain fields in UAT and Prod.

Logging of Client Side error in Mule flows

How to handle or log the client side error in best way. Say for Client enters the URL and he received 501 error. We need to log that error as well we need to log from which api call that error was occurred.
Can someone suggest. sorry, I cant give a example because its generic doubt in my mind
If any one suggests how to do. I will create the flow will share here for public use
You can't capture the HTTP status that the HTTP Listener sends automatically. For example a 404 (page not found), if there is no listener for that URL.
You can capture your own HTTP status that you set in your application, and do something before the flow ends.
Example:
<flow name="statusFlow" >
<http:listener doc:name="Listener" config-ref="HTTP_Listener_config" path="/page">
<http:response statusCode="#[vars.okStatus]" />
<http:error-response statusCode="#[vars.errorStatus]" />
</http:listener>
... set the variables ...
... log the variables ...
Note that the application can not know about status returned by something in front of your application, like a load balancer. That's the case for applications deployed to CloudHub and accessed through the load balancer.

Mule Error sending HTTP request SingleEndpointPool$ConnectCompletionHandler.cancelled

I've created a mule process API that calls a mule system API using an HTTP request, via the mule <http:request> tag. The system API in turn processes the request using a database call. The process and system APIs are deployed to cloud hub. I could successfully test the system API locally and from cloud hub. The process API though gives me the following error message.
********************************************************************************
Message : Error sending HTTP request.
Element : /get:\/terms:api-config/processors/0/getTermsImpl/subprocessors/0 # msu-test-p-sisinfo:implementation.xml:25 (httpSisInfoTerms)
--------------------------------------------------------------------------------
Exception stack is:
Error sending HTTP request. (org.mule.api.MessagingException)
org.glassfish.grizzly.connectionpool.SingleEndpointPool$ConnectCompletionHandler.cancelled(SingleEndpointPool.java:1284)
org.glassfish.grizzly.impl.SafeFutureImpl.notifyCompletionHandlers(SafeFutureImpl.java:185)
org.glassfish.grizzly.impl.SafeFutureImpl.done(SafeFutureImpl.java:277)
org.glassfish.grizzly.impl.SafeFutureImpl$Sync.innerCancel(SafeFutureImpl.java:389)
org.glassfish.grizzly.impl.SafeFutureImpl.cancel(SafeFutureImpl.java:247)
org.glassfish.grizzly.connectionpool.SingleEndpointPool$ConnectTimeoutWorker.doWork(SingleEndpointPool.java:1352)
org.glassfish.grizzly.connectionpool.SingleEndpointPool$ConnectTimeoutWorker.doWork(SingleEndpointPool.java:1344)
org.glassfish.grizzly.utils.DelayedExecutor$DelayedRunnable.run(DelayedExecutor.java:158)
org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
java.lang.Thread.run(Thread.java:745)
(set debug level logging or '-Dmule.verbose.exceptions=true' for everything)
********************************************************************************
The error references line 25 in the file implementation.xml of the process API. The contents of the file are listed below. Line 25 is the call to the http:request configurator defined in global.xml.
<sub-flow name="getTermsImpl">
<http:request config-ref="httpRequestConfig-sisinfo" path="api/terms" method="GET" doc:name="httpSisInfoTerms">
</http:request>
</sub-flow>
Any help is greatly appreciated!

Timeout error in Until Successful

We have a flow where we have implemented a soap client to send soap messages to Service provider.
We need to retry the service call for 3 times if it fails. So we have used HTTP Outbound Endpoint inside until successful scope.
It is doing retry as expected, but in case of success scenario, even if we get the response from the service, we are observing a time out error as below.
[DispatchThread: 1] org.apache.cxf.endpoint.ClientImpl: Timed out waiting for response to operation {http://support.cxf.module.mule.org/}invoke.
Observation:
I have removed the until successfully and had the HTTP Outbound endpoint directly, in this case there is no timeout error.
I later tried having until successfully and had an acknowledge expression to accept the response, still the same time out response.
failureExpression="#[message.inboundProperties['http.status'] != 200]" ackExpression="#[message.correlationId]"
Could any one please suggest, how to configure the until successful for accepting the response and not throwing time out error.
The ackExpression has nothing to do with "accept the response", it's for generating a value that will be used as the new message payload after the flow has passed the current event to the until-successful message processor.
Try setting a response-timeout on your outbound HTTP endpoint to see if it helps: maybe the default timeout used in the context of the until-successful scope is too big and creates this issue.
I found a solution for this.
Earlier I had only HttpOutbound endpoint inside Until-Successful and I am facing Timeout issue.
Now I included Soap component also inside Until-successful scope it is working fine.
Since until successful allow us to have only one component inside, I have wrapped soap component and HttpOutbound endpoint iside a processor chain.
<until-successful objectStore-ref="objectStore"
maxRetries="3" secondsBetweenRetries="2" deadLetterQueue-ref="xxxx"
doc:name="UntilSuccessfulService" >
<processor-chain doc:name="Processor Chain">
<cxf:jaxws-client operation="Request1" serviceClass="xxxxxxx" enableMuleSoapHeaders="true" doc:name="SOAP"/>
<http:outbound-endpoint exchange-pattern="request-response" method="POST" doc:name="HTTP" host="localhost" path="cService" port="xxxx" connector-ref="HTTP_HTTPS"/>
</processor-chain>
</until-successful>
Thanks David and all for your responses.