Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add object data when throwing an exception

I am coding a MVC 5 internet application, and I have a question in regards to throwing exceptions.

How is the best way to include object data when throwing an exception. I am wanting the exception to display specific object data when an email is sent to me when an exception occurs.

Some options I found:

  • I see that there is a public virtual IDictionary Data property. I could manually add data to the Data property.
  • I could also export the object data to an xml file and include this in the exception.
  • I could also maybe use reflection to get all the object fields.

Is there a recommended way to do this?

like image 707
user3736648 Avatar asked Dec 06 '22 22:12

user3736648


1 Answers

I would definitely go for the Data dictionary, since that is the closest to the actual exception. Also, it doesn't need access to the file system, etc. to work.

We use the Data dictionary ourselves a lot, and it helps to have a list of keys you, so you can easily reference the data again.

For example:

public const string SOME_KEY = "some_key";

Exception e = new Exception("some error");
e.Data.Add(SOME_KEY, someValue);

throw e;

Re-use it later:

object some_key = e.Data[SOME_KEY];
like image 197
Patrick Hofman Avatar answered Dec 15 '22 00:12

Patrick Hofman