I'm passing a List of Custom Objects to my Custom Exception Class and need to display all the objects in the message. How can I do this?
public class MissingUnitSNSException : Exception
{
public MissingUnitSNSException()
{
}
public MissingUnitSNSException(List<UnitViewModel> missingsns)
: base(String.Format("Serial Numbers not found: {0}", missingsns))
{
}
}
The error tells me the type of object, but I need the serial number attribute that's tied to each object in the list.
How about replacing missingsns
with a string of comma separated serial numbers. Like so:
string.join(", ", missingsns.Select(sns => sns.SerialNumber.ToString()))
This should list out the serial numbers like: A01, B01, C02, ...
Full line:
public MissingUnitSNSException(List<UnitViewModel> missingsns)
: base(String.Format("Serial Numbers not found: {0}",
string.join(", ", missingsns.Select(sns => sns.SerialNumber.ToString()))))
Please do not put important information into the message field. Getting them out there will be a pain for the user of your code!
Exceptions are classes. Add a readonly property for this data. Add it to what ToString() will return. This is one of the core rules of proper exception Handling:
Now with objects, you propably do not want to assign Reference to the Exception. Not only could the Exception keep the objects alive, there is a decent chance that Dispose is called on those instances before you get to process the Exception - making those references pretty useless.
As you seem content with "only" string data, a string[]
might be a good type. You do have to mind to shallow clone it when handing it out, but otherwise it is normal readonly Property of Exceptions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With