Kyle Kyle - 3 months ago 15
C# Question

Throw new exception with a code and a message

I'm parsing JSON from a server that contains

statusCode
and
statusMessage
... How do I throw these in my exception so that I don't have to use
if
-statements in my catch? So that I can have a generic process that handles all
exc.Code
and
exc.Message
, without having to look for it.

Here are my throws

else if (statusCode.Equals(26) && statusMessage.StartsWith("response sent", StringComparison.OrdinalIgnoreCase))
throw new Exception("Response sent - 26");
else if (statusCode.Equals(0))
throw new Exception("Fatal exception - 0");
else if (statusCode.Equals(3))
throw new Exception("Invalid parameters - 3");
else if (statusCode.Equals(24))
throw new Exception("Incorrect response Id - 24");


Here's my catch

try
{
dataResponse = GetStatus.RequestStatus(httpRequest);
}
catch (Exception exc)
{
if (exc.Message.ToString() == "Response sent - 26")
{
string errorCode = "26";
string errorMessage = "Response Sent";
// do things with erroCode and errorMessage...
}
else if (exc.Message.ToString() == "Fatal exception - 0")
{
string errorCode = "0";
string errorMessage = "Fatal exception";
//do things with errorCode and errorMessage...
}
// else ifs else ifs etc.. etc...
}
finally
{
// do things
}

Answer

There's a Data property on the Exception class. You could add your data to that.

It implements IDictionary... just add your key/value pairs to it, like this:

var ex = new Exception(string.Format("{0} - {1}", statusMessage, statusCode));
ex.Data.Add(statusCode, statusMessage);  // store "3" and "Invalid Parameters"
throw ex;

Then read it back out in your catch block. The Key and Value are both of type object, so you'll have to convert them back to their original types.

catch (Exception exc)
{
    var statusCode = exc.Data.Keys.Cast<string>().Single();  // retrieves "3"
    var statusMessage = exc.Data[statusCode].ToString();  // retrieves "Invalid Parameters"
}
Comments