I’m working in VB.NET – C# answers are fine.
I’m building a system for handling validation of XML against a specific XmlSchema. I have an instance of SchemaException for each error in my XML document, from which I can obtain the line number and position of the error, as well as the message. As far as I can tell, the only way of determining the specific error (invalid attribute, missing element etc.) is by reading the message string which is not reliable due to the possibility of MS changing it in the future and messages being localized.
I need to be able to differentiate between these errors without relying on the .Message property in order to display my own custom errors and highlight the errors within my text editor.
What is the correct way of telling these apart? It’s got to be possible, right?
More Info:
The LinePosition property of the exception does not always report the position in which I would like to start highlighting – all attribute related exceptions report the start of the attribute for instance and I would like to be able to highlight just the attribute value if that is the issue.
The SchemaException provides a SourceSchemaObject property which I could probably use to determine whether the problem was coming from an element or an attribute and, with a little luck, might allow me to work out what the exact error would be by extracting the XML text causing the error and comparing it to the SourceSchemaObject in some way but that feels like a very complicated and hacky solution – if I could just work out the specific error I could do it no problem with a bit of regex work.
Ok, I worked this out in the end. I figured that the exception had to have an internal value indicating the specific error in order to generate the message so I used ILSpy to gaze deep into its soul. It turns out it does indeed have an internal field called “res” that holds a string that maps to the error which we can access using reflection.
I wrote a little extension method that retrieves this error for me as a string.
This was great but I didn’t want to have to remember all of those string for Select Case scenarios so I wrote a script to convert the source that I extracted using ILSpy to an Enum and re-wrote the extension method like so:
Tah dah!
Now I can just do my error handling like this: