C#例外事件的額外資訊處理

C#例外事件的額外資訊處理

當發生例外時,我們都會希望將一些參數資訊也寫入Log,以便查看問題所在。

大多都會多寫Log函式,再把Exception與額外參數資訊傳入到此函式,而傳入函式多半都會使用Dictionary來存放較為彈性。

static void RunExceptionLogWithProperty(string text)
{
    Dictionary<string, string> extensionProperty = new Dictionary<string, string> { 
        {"text", text}
    };

    try
    {
        int i = int.Parse(text);
    }
    catch (Exception ex)
    {
        Console.WriteLine("RunExceptionLogWithProperty");
        ExceptionLogWithProperty(ex, extensionProperty);
    }
}

static void ExceptionLogWithProperty(Exception ex, Dictionary<string, string> extensionProperty)
{
    if (extensionProperty != null)
    {
        foreach (KeyValuePair<string, string> item in extensionProperty)
        {
            Console.WriteLine("Key: {0},\tValue: {1}", item.Key, item.Value);
        }
    }
    Console.WriteLine(ex);
}

 

但每次都必須要額外宣告Dictionary頗為麻煩,所以可以善用Exception內建的Data屬性,來放入額外資訊。

因Exception.Data的資料類型是IDictionary,所以用法與上述的方法一樣,差別在於取資料時,要改成DictionaryEntry,而不是KeyValuePair。

static void RunExceptionLog(string text)
{
    try
    {
        int i = int.Parse(text);
    }
    catch (Exception ex)
    {
        Console.WriteLine("ExceptionLog");
        ex.Data.Add("text", text);
        ExceptionLog(ex);
    }
}

static void ExceptionLog(Exception ex)
{
    Console.WriteLine("Extra details:");
    foreach (DictionaryEntry item in ex.Data)
    {
        Console.WriteLine("Key: {0},\tValue: {1}", item.Key.ToString(), item.Value);
    }
    Console.WriteLine(ex);
}

結果都是一樣的

 

創用 CC 授權條款
本著作由Chenting Weng製作,以創用CC 姓名標示 4.0 國際 授權條款釋出。
This work by Chenting Weng is licensed under a Creative Commons Attribution 4.0 International License.
Based on a work at https://dotblogs.com.tw/chentingw.

部分文章內容會引用到其他網站的簡介或圖片,若有侵犯到您的著作權,請留言告知,本人會儘快移除。
免責聲明:文章屬個人記事使用,僅供參考,若引用文章造成一切損失,本人不承擔任何責任。如有錯誤,歡迎留言告知。

Part of the content of the article will refer to the profile or picture of other websites.
If there is any infringement of your copyright, please leave a message and let me remove it as soon as possible.
Disclaimer:The article is for personal use and is for reference only. I will not bear any responsibility for any loss caused by quoting the article. If there is an error, please leave a message to inform.