Web服务异常处理

时间:2010-05-07 22:06:26

标签: .net exception-handling web-services

我有一个使用C#Webservice的Winforms应用程序。 如果WebService抛出异常我的客户端应用程序总是得到一个SoapException而不是“真正的”异常。

这是一个演示:

[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”,我只能通过解析Exception的消息属性来找出“真正的”异常:

        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 ---

有没有办法以某种方式完成这项工作?

2 个答案:

答案 0 :(得分:1)

根据我的经验,Web服务将返回响应中序列化的异常。然后由客户端对其进行反序列化并采取适当的措施。

快速谷歌搜索提出了这个问题:http://msdn.microsoft.com/en-us/library/ds492xtk%28vs.71%29.aspx

答案 1 :(得分:1)

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

这篇旧的但有用的MSDN文章可能对您有所帮助

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