questions/50164139/access-dictionary-items-in-data-property-of-exception-class

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Xml.Serialization;
using System.Xml;
using System.Xml.Linq;
using System.IO;
using System.Data;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO.Compression;

// https://stackoverflow.com/questions/50164139/access-dictionary-items-in-data-property-of-exception-class/50164278#50164278

	public static class Constants
	{
		public const string ExceptionMessageKey = "UI Error Message";
	}

    public class TestClass
    {
        public static void Test()
        {
			try
			{
				var ReasonCodeID = -1;
				
				Exception ex = new Exception("Datebase error");
				ex.Data.Add(Constants.ExceptionMessageKey, "Whoops! Something went wrong there. Please call (555)555-5555 " +
					"and notify them something is wrong with the Encounter Reason: " + ReasonCodeID);
				throw ex;
			}
			catch (Exception ex)
			{
				string text = ex.Data[Constants.ExceptionMessageKey]?.ToString();
				
				// IDIctionary get accessor should return null when key is missing, rather than throw an exception:
				string text2 = ex.Data["wrong key"]?.ToString();
				
				Console.WriteLine(text);
				Console.WriteLine(text2);
			}
        }
    }

	public class Program
	{
		public static void Main()
		{
			Console.WriteLine("Roslyn 2.0 Compiler; Environment version: " + Environment.Version);
			Console.WriteLine();

			try
			{
				TestClass.Test();
			}
			catch (Exception ex)
			{
				Console.WriteLine("Uncaught exception: ");
				Console.WriteLine(ex);
				throw;
			}
		}
	}
;