実際、あなたはあなたが言及した記事によって提案されたアプローチに従うことができます。子孫のWebパーツがオーバーライドするすべての仮想プロパティとメソッドに安全なオーバーライド可能オブジェクトを提供する必要があります。パターンは次のように説明できます。
- 例外をスローする可能性のあるコードでオーバーライドされるはずのすべての仮想プロパティとメソッドをオーバーライドしてシールします。
- 同じプロトタイプを使用してオーバーライド可能な仮想の対応物を作成し、必要に応じてそこから基本クラスを呼び出します。これは、子孫によってオーバーライドされることになっています。
- try&catchでシールされたメンバーから新しいオーバーライド可能オブジェクトを呼び出し、そこでキャッチされた場合は例外を覚えておいてください。
- レンダリング方法は、通常のコンテンツまたは記憶されたエラーメッセージのいずれかをレンダリングします。
これは、私が使用する基本クラスの胴体です。
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
}
---フェルダ