WCF異常相關經驗分享
WCF框架作為一款由微軟開發(fā)的幫助解決跨平臺操作的方案,深受開發(fā)人員喜愛。在這里主要介紹一下WCF異常的相關知識。希望對大家有用。#t#
WCF異常將服務異常(Exception)轉換成 SOAP faults,傳遞到客戶端后再次轉換成 Exception。只不過缺省情況下,我們很難從中獲取有意義的信息。
- < ServiceContract()> _
- Public Interface IService1
- < OperationContract()> _
- Function GetData(ByVal
value As Integer) As String - End Interface
- Public Class Service1
- Implements IService1
- Public Function GetData(ByVal
value As Integer) As String
Implements IService1.GetData - Throw New Exception("發(fā)生錯誤。")
- Return String.Format
("You entered: {0}", value) - End Function
- End Class
拋出來的WCF異常信息:
接收對 http://localhost:8731/Design_Time_Addresses/WcfServiceLibrary1/Service1/ 的 HTTP 響應時發(fā)生錯誤。這可能是由于服務終結點綁定未使用 HTTP 協(xié)議造成的。這還可能是由于服務器中止了 HTTP 請求上下文(可能由于服務關閉)所致。有關詳細信息,請參閱服務器日志。
Server stack trace:
在 System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
在 System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
不太好理解
當然,WCF 會提供一個包裝異常類 FaultException 來幫助我們處理這些問題。
發(fā)生錯誤。
Server stack trace:
在 System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
在 System.Servi
這樣就對WCF異常好理解多了,所以在服務端拋出異常時,使用FaultException 異常類。
另外,我們還可以通過 FaultContractAttribute 傳遞更詳細的異常信息給客戶端。
- < ServiceContract()> _
- Public Interface IService1
- < OperationContract(),
FaultContract(GetType(Fault))> _- Function GetData(ByVal
value As Integer) As String- End Interface
- Public Class Service1
- Implements IService1
- Public Function GetData(
ByVal value As Integer) As
String Implements IService1.GetData- Dim f As New Fault
- f.ErrorCode = 200
- f.Message = "發(fā)生錯誤"
- Throw New FaultException
(Of Fault)(f, f.Message)- Return String.Format("You
entered: {0}", value)- End Function
- End Class
- < DataContract()> _
- Public Class Fault
- < DataMember()> _
- Public ErrorCode As Integer
- < DataMember()> _
- Public Message As String
String = String.Empty- End Class
客戶端代碼:
- Sub Main()
- Dim url As String = "http:/
/localhost:8731/Design_Time_
Addresses/WcfServiceLibrary1
/Service1/mex"- Dim host As New System.Servi
ceModel.ServiceHost(GetType
(WcfServiceLibrary1.Service1))- host.AddServiceEndpoint(GetType
(WcfServiceLibrary1.IService1),
New System.ServiceModel.Basic
HttpBinding(), url)- host.Open()
- Console.WriteLine(host.State.ToString)
- Dim c = New System.ServiceModel
.ChannelFactory(Of WcfServiceL
ibrary1.IService1)(New System.
ServiceModel.BasicHttpBinding, url)- Dim s As WcfServiceLibrary1.
IService1 = c.CreateChannel- Try
- Console.WriteLine(s.GetData(1))
- Catch ex As System.ServiceModel.
FaultException(Of WcfService
Library1.Fault)- Console.WriteLine("錯誤代碼:"
& ex.Detail.ErrorCode)- Console.WriteLine("錯誤消息:"
& ex.Detail.Message)- End Try
- Console.ReadKey()
- End Sub
這樣WCF異常信息,就可以傳遞到客戶端了。