SOAP Response Codes

October 20th, 2011 Blog 0 Comments

I recently had an issue where as a part of a SOAP fault response I wanted to return a HTML response code that better represented what the error was – in this case that a particular record requested via the service did not exist for the supplied identifier.

This sort of request might return a response code of 200 in a more typical web request with perhaps a relevant error message or similar. It felt that within a service – no human action, intervention or response – something a little more informative or appropriate was required such as 422 Unprocessable Entity.

To achieve this I defined an out fault interceptor as follows.

        <jaxws:outFaultInterceptors>
            <bean class="mypackage.MyServiceOutInterceptor"/>
        </jaxws:outFaultInterceptors>

The implementation was rather simple in the end:

public class MyServiceOutInterceptor extends AbstractSoapInterceptor {

    public MyServiceOutInterceptor() {
        super(Phase.SEND);
    }

    public void handleMessage(SoapMessage soapMessage) throws Fault {
        
        Set<Class<?>> formats = soapMessage.getContentFormats();
        for (Class<?> format : formats) {
            
            Object content = soapMessage.getContent(format);
            if (isServiceError(content)) {
                ServiceFaultException exception = asServiceError(content);
                soapMessage.put(org.apache.cxf.message.Message.RESPONSE_CODE, exception.getResponseCode());
                break;
            }
            
        }
        
    }

    private ServiceFaultException asServiceError(Object content) {
        return (ServiceFaultException) ((Fault) content).getCause();
    }

    private boolean isServiceError(Object content) {
        return (content.getClass().isAssignableFrom(SoapFault.class)) 
                && (((Fault) content).getCause() instanceof ServiceFaultException);
    }

}

We check that we have a valid error, and then deliberately set the response code for the SOAP message.

The ServiceFaultException class shown above is defined as a web fault using @WebFault and the relevant error message and code is set as required.

So, the merits of returning 422 for an entity that can not be found aside, the above demonstrates how to change the response code returned as a part of a SOAP fault to anything you like.

RIP Steve Jobs
UnixBench

About Takis Diakoumis

I am a software developer from Melbourne, Australia. I promote and support open source software and release whatever I can of my own work under the GPL license.

» has written 30 posts

No Comments


 

Categories