Java Mailing List Archive

http://www.junlu.com/

Home » user.castor »

[castor-user] [XML] Getting a proper error message when validating (unmarshalling)
 a schema

Ruchira Alwis

2010-05-31


Author LoginPost Reply
Hi

I’m developing a web based application using Java and we have a XSD schema defined in order to validate the incoming requests (web-service) in XMLs. I’m using castor 1.1.2.1 and don’t use any XML mapping.

I first created the stubs using the ‘XML code generator’ by providing the XSD. Then validate the XML data runtime against to the generated stubs.
All good and working great for the happy path scenario.

However, If it encounters invalid data from XML, the error message returning from Castor is not user friendly. (Though it is developer friendly)
I need to show a proper error message saying which field is invalid and for this I would like to define an error message inside the XSD (in each field) and I would like to get that error when invalid data is encountered.

For ex: In my XSD I have some customer data (email) defined as follows

<xs:simpleType name="emailType">
       <xs:annotation>
           <xs:documentation>A valid email address.
            </xs:documentation>
            <errorMessage>Email address provided is invalid</errorMessage>
       </xs:annotation>
       <xs:restriction base="xs:string">
           <xs:minLength value="1"/>
           <xs:maxLength value="50"/>
           <xs:pattern value="[A-Za-z0-9_]+([-+.'][A-Za-z0-9_]+)*@[A-Za-z0-9_]+([-.][A-Za-z0-9_]+)*\.[A-Za-z0-9_]+([-.][A-Za-z0-9_]+)*" />
       </xs:restriction>
    </xs:simpleType>

<xs:element name="email" type="emailType" />

If the request data is not according to the given regex pattern, I need to pick the message defined in <errorMessage> and return it to the user.

Alternatively, I can catch the exception and do some string comparison and find the error-field, then construct a proper error message. But I feel its not a good design because we have to deal with more than 25 XSDs depending on the request type we get and the business wants a proper meaningful error message (preferred with a pre-defined ErrorCode)
Or, please let me know the insides of how the validations happens in Castor.

I googled using various search criteria and couldn’t find a good way of doing this.

Really appreciate if you can give me a good suggestion to solve my problem as I feel it is a kind of a generic requirement most of the people would be facing during building an web application.

Cheers
Ruchiras
©2008 junlu.com - Jax Systems, LLC, U.S.A.