先前介紹過用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. 訊息以及錯誤所在程式碼列數等偵錯資訊,開發期間要排除問題就簡單多了。


Comments

Be the first to post a comment

Post a comment