Thursday, July 5, 2012

Error Handling in WSO2 ESB

When a Proxy Service or a Sequence which mediate messages, is considered, error handling would be a key concern. Depending on the error type, we might need to send a fault message, custom response etc.

WSO2 ESB makes our life easier by allowing us to specify a custom fault sequence for error handling. i.e. It gives the flexibility to use mediator and do various tasks even when an error occurred.

Following is a sample sequence which logs the error details and sends a custom message to the client when an error occurs. Further, if you need to send a SOAP Fault, then Fault mediator can be used instead of Payload Factory mediator.
<sequence name="myErrorSequence">
    <header name="To" action="remove"/>
    <property name="RESPONSE" value="true"/>
    <property name="NO_ENTITY_BODY" scope="axis2" action="remove"/>

    <log level="custom">
        <property name="error-message" expression="get-property('ERROR_MESSAGE')"/>
        <property name="error-code" expression="get-property('ERROR_CODE')"/>
        <property name="error-detail" expression="get-property('ERROR_DETAIL')"/>
        <property name="error-exception" expression="get-property('ERROR_EXCEPTION')"/>
    </log>

    <payloadFactory>
        <format>
            <ns:MyResponse xmlns:ns="http://services.samples">
                <ns:Error/>
            </ns:MyResponse>
        </format>
    </payloadFactory>
    <send/>
</sequence> 

As response might be sending even without going to the outSequence, we need to remove the To header and specify the other two properties named RESPONSE and NO_ENTITY_BODY.

You can also get the details of the error occurred using properties named ERROR_MESSAGE, ERROR_CODE, ERROR_DETAIL and ERROR_EXCEPTION.

After you added the above sequence into the configuration, you can refer it as below from a Proxy or a Sequence.

For a Sequence :
<sequence name="mySequence" onerror="myErrorSequence">
.......
</sequence>
For a Proxy Service :
<proxy name="MyProxy" xmlns="http://ws.apache.org/ns/synapse">
    <target faultSequence="myErrorSequence">
    ......
    </target>
</proxy>

5 comments:

  1. Hi Wageesha,could you please explain me about Mediators (LOG,PROPERTY,PAYLOADFACTORY )

    ReplyDelete
  2. I getting confusion on Mediators, could you please explain all in details, it would be great help to me.

    ReplyDelete
  3. @Anil, please go through the link [1]. It will help you to get a good understanding about all of the above.

    [1] http://docs.wso2.org/wiki/display/ESB450/Mediators

    ReplyDelete
  4. hi
    please will help for this
    http://stackoverflow.com/questions/15290696/error-handling-is-not-working-in-wso2esb
    http://stackoverflow.com/questions/15332501/how-can-i-handle-error-sequence-in-wso2esb

    ReplyDelete
  5. i get empty when it return to the client. How can I get the error_message in the tag error

    ReplyDelete