Server-Side XML Validation with CXF Webservice

You can override validation error messages, inserting a line number, by using a custom ValidationEventHandler:

package example;

import javax.xml.bind.ValidationEvent;
import javax.xml.bind.helpers.DefaultValidationEventHandler;

public class MyValidationEventHandler extends DefaultValidationEventHandler {    
    public boolean handleEvent(ValidationEvent event) {
        if (event.getSeverity() == ValidationEvent.WARNING) {
            return super.handleEvent(event);
        } else {
            throw new RuntimeException(event.getMessage()
                + " [line:"+event.getLocator().getLineNumber()+"]");

If you configure your endpoint to use this handler:

<jaxws:endpoint id="someEndpoint" implementor="#someImpl" address="/impl">
        <entry key="schema-validation-enabled" value="true" />
        <entry key="jaxb-validation-event-handler">
            <bean class="example.MyValidationEventHandler" />

Then you will get SOAP faults that look like this:

<soap:Envelope xmlns:soap="">
            <faultstring>Unmarshalling Error: Not a number: xyz [line: 6]</faultstring>

The jaxb-validation-event-handler property was only added to CXF pretty recently, so you need to make sure you’re using the latest version – I tested this with 2.2.5.

Leave a Comment