Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I display a list of objects in an Exception?

Tags:

c#

exception

list

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.

like image 311
Afdufsko Avatar asked Aug 02 '19 20:08

Afdufsko


2 Answers

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()))))
like image 75
dvo Avatar answered Nov 15 '22 01:11

dvo


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:

  • https://blogs.msdn.microsoft.com/ericlippert/2008/09/10/vexing-exceptions/
  • https://www.codeproject.com/Articles/9538/Exception-Handling-Best-Practices-in-NET

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.

like image 35
Christopher Avatar answered Nov 14 '22 23:11

Christopher