TIPS-取得WebClient錯誤的詳細訊息

先前介紹過用WebClient存取網站內容的技巧,在實務上有個狀況: 當存取對象的ASPX發生程式錯誤,呼叫端只會得知是HTTP 500應用程式出錯,但錯誤細節無從得知。

例如以下範例:

    protected void Page_Load(object sender, EventArgs e)
    {
        //加入故意產生錯誤邏輯
        if (Request["err"] != null)
            throw new NotImplementedException();
 
        WebClient wc2 = new WebClient();
        string s = wc2.DownloadString(
            "httq://localhost/MyApp/ShowWebClientError.aspx?err=true");
        Response.Write("OK");
        Response.End();
    }

網頁以WebClient呼叫自己,被呼叫時故意抛出一個NotImplementedException,此時我們得到的結果是The remote server returned an error: (500) Internal Server Error. 。雖知網頁出錯,卻無法得知背後肇因於NotImplementedException。

以上困擾,有個解決方法是捕捉WebException,從中取出錯誤網頁的Response內容,便可提供進一步的偵錯資訊。

    protected void Page_Load(object sender, EventArgs e)
    {
        //加入故意產生錯誤邏輯
        if (Request["err"] != null)
            throw new NotImplementedException();
 
        try
        {
            WebClient wc = new WebClient();
            string r = wc.DownloadString(
                "httq://localhost/MyApp/ShowWebClientError.aspx?err=true");
            Response.Write("OK");
        }
        catch (WebException we)
        {
            using (StreamReader sr = 
                new StreamReader(we.Response.GetResponseStream()))
            {
              //實務上可將錯誤資訊網頁寫入Log檔備查,
                //此處只將錯誤訊息完整傳回當示範
                Response.Write(sr.ReadToEnd());
            }
        }
        Response.End();
    }

執行以上程式,將可看到The method or operation is not implemented. 訊息以及錯誤所在程式碼列數等偵錯資訊,開發期間要排除問題就簡單多了。

歡迎推文分享:
Published 28 July 2010 08:43 PM 由 Jeffrey
Filed under: ,
Views: 8,047



意見

沒有意見

你的看法呢?

(必要的) 
(必要的) 
(選擇性的)
(必要的) 
(提醒: 因快取機制,您的留言幾分鐘後才會顯示在網站,請耐心稍候)

5 + 3 =

搜尋

Go

<July 2010>
SunMonTueWedThuFriSat
27282930123
45678910
11121314151617
18192021222324
25262728293031
1234567
 
RSS
創用 CC 授權條款
【廣告】
twMVC

Tags 分類檢視
關於作者

一個醉心技術又酷愛分享的Coding魔人,十年的IT職場生涯,寫過系統、管過專案, 也帶過團隊,最後還是無怨無悔地選擇了技術鑽研這條路,近年來則以做一個"有為的中年人"自許。

文章典藏
其他功能

這個部落格


Syndication