... ...
Assembly callingAssemply = Assembly.GetCallingAssembly();
Type exceptionType = GetExceptionType(callingAssemply); //獲得使用者異常類型定義
Exception e = null;
try {
try {
e = Activator.CreateInstance(exceptionType, new object[]{UserExceptionMessage}, null) as Exception;
}
catch {}
//if no exists constructor with message parameter, use no parameters constructor.
if (e == null) e = Activator.CreateInstance(exceptionType) as Exception;
}catch(Exception ex) {
throw new SoapExceptionHelperException(userExceptionClass, ex);
}
// 項目引用中引入異常定義所在的整合塊
...
SoapExceptionHelper helper = new SoapExceptionHelper(se);
Type type = Type.GetType(helper.UserExceptionClass, "<異常類所在的整合塊>");
Exception e = helper.GetUserException(type);
屏蔽SoapException
Web Service用戶端代理類可以在捕獲SoapException後重新拋出原來的異常,使用這種機制,可以有效屏蔽Web Service異常處理的差異,使應用程式採用一致的本地方式處理異常。下面的代碼修改Visual Studio產生的Web Service Client Proxy Class(Reference.cs檔案)實現了這種機制(加粗的部分為新增的代碼):
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/TestException", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void TestException() {
try{
this.Invoke("TestException", new object[0]);
}catch(SoapException se){
SoapExceptionHelper helper = new SoapExceptionHelper(se);
if (helper.IsUserException) throw helper.UserException; //rethrow user exception
else throw;
}
}