其實,你可以按照你提到的文章建議的方法。您只需爲所有虛擬屬性和您的後代Web部件要覆蓋的方法提供安全覆蓋。這個模式可以描述爲:
- 覆蓋並密封每個虛擬屬性和方法應該被可以拋出異常的代碼覆蓋。
- 使用相同的原型創建可覆蓋的虛擬對象,並根據需要從中調用基類。這應該被你的後代覆蓋。
- 從密封成員中調用新的可覆蓋的成員,並嘗試執行&捕獲,並記住捕獲到的異常。
- 呈現方法呈現通常的內容或記憶中的錯誤消息。
這是我使用的基類的軀幹:
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
您可以發佈您在沙箱中使用您的樣品?我想你得到的消息實際上是未處理的異常冒泡。在文章中,作者只是簡單地包裝所有事件。我認爲這種方法應該工作得很好。 – Roman 2012-04-25 04:16:55