我希望为使用沙盒webpart的SharePoint解决方案开发错误处理策略。我最初正在研究基于此article的一般异常处理方法,但这不适用于沙盒webpart。一旦在沙箱中抛出了未处理的异常,用户代码服务似乎就会获得控制权,因此不会到达基本Web部件中的异常处理。是否有针对沙盒解决方案的既定错误处理方法?
是否有人知道确定何时在沙盒webpart中抛出未处理的异常的方法,如果只是为了将显示的错误消息更改为更友好的用户消息?我想替换标准的“ Web部件错误:部分信任应用程序域中的沙盒代码包装器的Execute方法引发了未处理的异常:至少发生了意外错误。”消息。< / p>
谢谢,MagicAndi。
答案 0 :(得分:1)
实际上,您可以按照您提到的文章建议的方法。您只需为后代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
}
---费达