When you send a HTTP request to an API in WSO2 ESB, if the requested API resource URL does not comply with the API resource definition, ESB returns HTTP 202 accepted response to the user. Due to this behavior, the client is unable to distinguish if they have made an error. We can use the following procedure to return a fault to the client in case of non-matching API resource is requested by client.
Step 1:
Suppose, we have an API similar to the following. Note that, the target web service is a JAXRS web application (jaxrs_basic) which is included in WSO2 Application Server by default.<api xmlns="http://ws.apache.org/ns/synapse" name="jaxrs" context="/jaxrs">
<resource methods="GET" uri-template="/customers/{id}">
<inSequence>
<send>
<endpoint>
<address uri="http://localhost:9764/jaxrs_basic/services/customers/customerservice"/>
</endpoint>
</send>
</inSequence>
<outSequence>
<send/>
</outSequence>
</resource>
</api>
Step 2:
Send the following HTTP GET request to the above API. (You can use a soapUI web testcase as instructed in one of my previous blog posts).GET http://localhost:8280/jaxrs/customers-wrong/123
Step 3:
You will get HTTP 202 accepted response because the request URL does not match with the resource url-template defined in the API.Step 4:
Now, add the following fault handling sequence in ESB. Once the API receives a request which does not match with any of the resource url patterns/templates, this sequence will be invoked. Make sure to name the sequence as _resource_mismatch_handler_<sequence xmlns="http://ws.apache.org/ns/synapse" name="_resource_mismatch_handler_">
<payloadFactory>
<format>
<tp:fault xmlns:tp="http://test.com">
<tp:code>404</tp:code>
<tp:type>Status report</tp:type>
<tp:message>Not Found</tp:message>
<tp:description>The requested resource (/$1) is not available.</tp:description>
</tp:fault>
</format>
<args>
<arg xmlns:ns="http://org.apache.synapse/xsd" expression="$axis2:REST_URL_POSTFIX"/>
</args>
</payloadFactory>
<property name="RESPONSE" value="true" scope="default"/>
<property name="NO_ENTITY_BODY" action="remove" scope="axis2"/>
<property name="HTTP_SC" value="404" scope="axis2"/>
<header name="To" action="remove"/>
<send/>
<drop/>
</sequence>
Step 5:
Send the above HTTP GET request again. This time, you will get a proper error as shown below.HTTP/1.1 404 Not Found
Content-Type: application/xml; charset=UTF-8
Accept-Encoding: gzip,deflate
Host: 10.100.3.37:8280
Date: Fri, 16 Nov 2012 06:06:51 GMT
Server: Synapse-HttpComponents-NIO
Transfer-Encoding: chunked