0

我正在爲使用沙盒裝web部件的SharePoint解決方案開發錯誤處理策略。我最初正在尋找一種基於此article的常規異常處理方法,但這不適用於沙盒Web部件。一旦在沙箱中拋出了未處理的異常,用戶代碼服務似乎將接管控制權,從而未達到基礎Web部件中的異常處理。是否有任何建立的沙盒解決方案的錯誤處理方法?沙盒SharePoint解決方案的錯誤處理策略

是否有人知道確定什麼時候在沙盒Web部件中拋出未處理的異常的方法,只要將顯示的錯誤消息更改爲更加用戶友好的消息?我想替換標準「Web部件錯誤:未處理的異常是由部分信任應用程序域中的沙盒代碼包裝器的Execute方法引發的:發生了意外錯誤。至少有」消息。

謝謝,MagicAndi。

+1

您可以發佈您在沙箱中使用您的樣品?我想你得到的消息實際上是未處理的異常冒泡。在文章中,作者只是簡單地包裝所有事件。我認爲這種方法應該工作得很好。 – Roman 2012-04-25 04:16:55

回答

1

其實,你可以按照你提到的文章建議的方法。您只需爲所有虛擬屬性和您的後代Web部件要覆蓋的方法提供安全覆蓋。這個模式可以描述爲:

  1. 覆蓋並密封每個虛擬屬性和方法應該被可以拋出異常的代碼覆蓋。
  2. 使用相同的原型創建可覆蓋的虛擬對象,並根據需要從中調用基類。這應該被你的後代覆蓋。
  3. 從密封成員中調用新的可覆蓋的成員,並嘗試執行&捕獲,並記住捕獲到的異常。
  4. 呈現方法呈現通常的內容或記憶中的錯誤消息。

這是我使用的基類的軀幹:

public class ErrorSafeWebPart : WebPart { 

    #region Error remembering and rendering 

    public Exception Error { get; private set; } 

    // Can be used to skip some code later that needs not 
    // be performed if the web part renders just the error. 
    public bool HasFailed { get { return Error != null; } } 

    // Remembers just the first error; following errors are 
    // usually a consequence of the first one. 
    public void RememberError(Exception error) { 
     if (Error != null) 
      Error = error; 
    } 

    // You can do much better error rendering than this code... 
    protected virtual void RenderError(HtmlTextWriter writer) { 
     writer.WriteEncodedText(Error.ToString()); 
    } 

    #endregion 

    #region Overriddables guarded against unhandled exceptions 

    // Descendant classes are supposed to override the new DoXxx 
    // methods instead of the original overridables They should 
    // not catch exceptions and leave it on this class. 

    protected override sealed void CreateChildControls() { 
     if (!HasFailed) 
      try { 
       DoCreateChildControls(); 
      } catch (Exception exception) { 
       RememberError(exception); 
      } 
    } 

    protected virtual void DoCreateChildControls() 
    {} 

    protected override sealed void OnInit(EventArgs e) { 
     if (!HasFailed) 
      try { 
       DoOnInit(e); 
      } catch (Exception exception) { 
       RememberError(exception); 
      } 
    } 

    protected virtual void DoOnInit(EventArgs e) { 
     base.OnInit(e); 
    } 

    // Continue similarly with OnInit, OnLoad, OnPreRender, OnUnload 
    // and/or others that are usually overridden and should be guarded. 

    protected override sealed void RenderContents(HtmlTextWriter writer) { 
     // Try to render the normal contents if there was no error. 
     if (!HasFailed) 
      try { 
       DoRenderContents(writer); 
      } catch (Exception exception) { 
       RememberError(exception); 
      } 
     // If an error occurred in any phase render it now. 
     if (HasFailed) 
      RenderError(writer); 
    } 

    protected virtual void DoRenderContents(HtmlTextWriter writer) { 
     base.RenderContents(writer); 
    } 

    #endregion 
} 

--- Ferda