2010-05-07 161 views
2

我有一个使用C#Web服务的Winforms应用程序。 如果WebService引发异常,我的客户端应用程序总是得到一个SoapException而不是“真正的”异常。Web服务异常处理

这里有一个演示:

[WebService(Namespace = "http://tempuri.org/")] 
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
[System.ComponentModel.ToolboxItem(false)] 
public class Service1 : System.Web.Services.WebService 
{ 
    [WebMethod] 
    public string HelloWorld() 
    { 
     throw new IndexOutOfRangeException("just a demo exception"); 
    } 
} 

现在,在客户端,我希望能够以不同的方式来处理不同的异常。

 try 
     { 
      ServiceReference1.Service1SoapClient client 
       = new ServiceReference1.Service1SoapClient(); 
      Button1.Text = client.HelloWorld(); 
     } 
     catch (IndexOutOfRangeException ex) 
     { 
      // I know how to handle IndexOutOfRangeException 
      // but this block is never reached 
     } 
     catch (MyOwnException ex) 
     { 
      // I know how to handle MyOwnException 
      // but this block is never reached 
     } 
     catch (System.ServiceModel.FaultException ex) 
     { 
      // I always end in this block 
     } 

但是,这并不工作,因为我总是得到“System.ServiceModel.FaultException”我只能通过解析异常的消息财产找出“真正的”异常:

 System.Web.Services.Protocols.SoapException: Server was unable 
     to process request. ---> System.IndexOutOfRangeException: just a demo\n 
      at SoapExceptionTest.Service1.Service1.HelloWorld() in ... 
     --- End of inner exception stack trace --- 

是有办法让这项工作以某种方式?

回答

1

你应该记住,SOAP不知道.NET异常,在Web服务中的错误返回故障。您应该考虑设计您的Web服务,以便它们捕获错误并将错误信息作为响应的一部分返回,并由您的客户端代码处理。或者yu可以使用SOAP故障机制。

这个古老而有用的MSDN文章可以帮助你

http://msdn.microsoft.com/en-us/library/aa480514.aspx