2

When a date like "2017-06-27" is inside of a large XML document containing many other dates and stings to be deserialized, a System.FormatException is thrown with the message "String was not recognized as a valid DateTime." Similar exceptions are thrown for Boolean.Parse, Guid.Parse, etc. (as indicated in the FormatException docs) and this question applies to all of them.

How do I determine which string caused the FormatException?

I feel like this should be a parameter in the FormatException class, but if there is any way at all to get at it, I'd like to know. I was debugging deep in Microsoft's Deserialization code and ran against a brick wall when it wouldn't Step-Into further (not that this sledgehammer approach would have been elegant, even if it had worked).

Note: this is not a case for DateTime.ParseExact, as I don't know what format the string will be in, nor is it even a question about parsing dates, but it is a question about the exception itself and how to get more useful information out of it.

NH.
  • 2,240
  • 2
  • 23
  • 37

1 Answers1

2

The approximate coordinates of the problem are included in the exception message.

System.InvalidOperationException: There is an error in XML document (4, 4). ---> System.FormatException: Input string was not in a correct format. at System.DateTime.Parse(String str) etc.....

John Wu
  • 50,556
  • 8
  • 44
  • 80
  • Thank you, that is somewhat helpful. What units are the coordinates in, though, and what does "approximate" mean? My Exception message was "There is an error in XML document (10, 46)." but the offender was not on line 10 (there isn't much at all on line 10). – NH. Jun 28 '17 at 19:08
  • That would be line 10, character 46. Sometimes the location seems off because the offending character has a remote effect, e.g. an unclosed quote won't cause the parser to blow up until the next opening quote is encountered, because everything in between looks like part of the string. – John Wu Jun 28 '17 at 20:03
  • OK, the remote effect makes sense, but why would it have a fictional character count on the line? Line 10 only has 11 characters, including whitespace. – NH. Jun 29 '17 at 15:15
  • Yeah it's way off for me sometimes too. I think it depends on a lot of factors, e.g. encoding, external files, whether there is an XML envelope, who knows. I'd probably need to see your entire XML to figure it out, and I can't guarantee I could. – John Wu Jun 29 '17 at 15:45
  • 1
    One thing to look out for is when it says (1, 1), that often means the buffer didn't get populated, e.g. a failure occurred earlier but got swallowed. – John Wu Jun 29 '17 at 15:47