0

I am trying to catch an exception when my XSD is invalid and just display a message on the console detailing to the user what went wrong. However the message that is displayed on the console is not as I expected.

try
{
    // doing stuff here
}
catch (XmlException e)
{
    Console.WriteLine("ERROR: Schema " + e.Message);
    return false;
}

I expected the output to be something like:

"ERROR: Schema ' is an unexpected token. The expected token is '>'. Line 15, position 38."

However the output that I get is:

"' is an unexpected token. The expected token is '>'. Line 15, position 38."

My string at the beginning is not displayed before the message.

I have tried storing the values in two strings and tried concatenating those 2 string with no success. Ideally I would like one string that contains the concatenation of both the 'ERROR' part and the message produced by the exception.

Dan Smith
  • 280
  • 3
  • 13
  • 1
    If you debug, does it hit that breakpoint? It could be possible that you're catching the wrong exception – Dan Drews Aug 06 '14 at 16:37
  • Why is there only one single quote at the start of the message? I think that's a big clue. I would expect single quotes around the unexpected token. – brianestey Aug 06 '14 at 16:38
  • I have changed it to Catch(Exception e) and the same behavior results – Dan Smith Aug 06 '14 at 16:46

2 Answers2

2

I think your schema contains a newline. The text ERROR: Schema ' must be somewhere higher in the output window.

You can check this using:

catch (XmlException e)
{
    string message = "ERROR: Schema " + e.Message;
    message = message.Replace(Environment.NewLine, "");
    message = message.Replace("\n", "");
    message = message.Replace("\r", "");

    Console.WriteLine(message);
    return false;
}
Yogesh
  • 14,498
  • 6
  • 44
  • 69
  • This produces the same result: ' is an unexpected token. The expected token is '>'. Line 15, position 38. – Dan Smith Aug 06 '14 at 16:46
  • That did the trick! So I guess there was some whitespace character? I don't understand why I didn't see both parts of the output anywhere on the console though? – Dan Smith Aug 06 '14 at 16:49
  • 1
    If you can't see `ERROR: Schema '` higher up somewhere, that means your schema contained a carriage return (`\r`). – Yogesh Aug 06 '14 at 16:52
  • Good thinking Yogesh, without the actual console output at hand. +1. – Emile Aug 06 '14 at 19:39
0

Try with:

try
{
    // doing stuff here
}
catch (XmlException e)
{
    errorMessage = "ERROR: Schema " + e.Message.toString();

    Console.WriteLine(errorMessage );
    return false;
}
Benjamin RD
  • 11,516
  • 14
  • 87
  • 157