I've created a custom exception for a very specific problem that can go wrong. I receive data from another system, and I raise the exception if it bombs while trying to parse that data. In my custom exception, I added a field called "ResponseData", so I can track exactly what my code couldn't handle.
In custom exceptions such as this one, should that extra response data go into the exception "message"? If it goes there, the message could be huge. I kind of want it there because I'm using Elmah, and that's how I can get at that data.
So the question is either: - How can I get Elmah to record extra information from a field in a custom exception OR - Should extra exception details go into the "message" property?
In custom exceptions such as this one, should that extra response data go into the exception "message"?
No, as Sören already pointed out. However, your exception type could override ToString
and sensibly add the response data information there. This is a perfectly normal practice followed by many of the exception types in the BCL (Base Class Library) so you will not find yourself swimming against the tide. For example, have a look at the System.IO.FileNotFoundException.ToString implementation in SSCLI (Rotor):
public override String ToString()
{
String s = GetType().FullName + ": " + Message;
if (_fileName != null && _fileName.Length != 0)
s += Environment.NewLine + String.Format(Environment.GetResourceString("IO.FileName_Name"), _fileName);
if (InnerException != null)
s = s + " ---> " + InnerException.ToString();
if (StackTrace != null)
s += Environment.NewLine + StackTrace;
try
{
if(FusionLog!=null)
{
if (s==null)
s=" ";
s+=Environment.NewLine;
s+=Environment.NewLine;
s+="Fusion log follows: ";
s+=Environment.NewLine;
s+=FusionLog;
}
}
catch(SecurityException)
{
}
return s;
}
As you can see, it appends the content of FusionLog property, which represent extra information in case of assembly load failures.
How can I get Elmah to record extra information from a field in a custom exception
ELMAH stores the result of calling ToString
on an exception as the details of the error so if you have ToString
implemented as prescribed, the information would get logged without further work. The only issue is that the logged detail will be unstructured text.