【问题标题】:How to catch a web service exception如何捕获 Web 服务异常
【发布时间】:2012-07-23 11:56:36
【问题描述】:

如何从返回自定义对象的 Web 服务中捕获异常?

我看过this 的帖子,但它似乎没有显示如何获取服务引发的异常。

我可以提取 SOAP 异常,但我希望能够获取 Web 服务返回的原始异常。我查看了此时设置的变量,似乎在任何地方都看不到异常,我只是看到:

"Server was unable to process request. ---> Exception of type 
    'RestoreCommon.ConsignmentNotFoundException' was thrown."

    try
    {
        Consignment cons = WebServiceRequest.Instance.Service
            .getConsignmentDetails(txtConsignmentNumber.Text);
            lblReceiverName.Text = cons.Receiver.Name;
    }
    catch (ConsignmentNotFoundException)
    {
        MessageBox.Show("Consignment could not be found!");
    }

这可能吗?

【问题讨论】:

    标签: c# web-services exception


    【解决方案1】:

    简而言之,没有。

    Web 服务总是会抛出 SOAP 错误。在您的代码中,

    1. MessageBox 旨在用于 Windows 窗体,而不能用于其他任何地方。
    2. 您可以抛出此异常,并在客户端应用程序中处理 SOAP 错误。

    编辑:如果您不想将异常发送给客户端,您可以这样做:

    class BaseResponse
        {
            public bool HasErrors
            {
                get;
                set;
            }
    
            public Collection<String> Errors
            {
                get;
                set;
            }
        }
    

    每个 WebMethod 响应都必须继承自此类。现在,这就是您的 WebMethod 块的样子:

    public ConcreteResponse SomeWebMethod()
            {
                ConcreteResponse response = new ConcreteResponse();
    
                try
                {
                    // Processing here
                }
                catch (Exception exception)
                {
                    // Log the actual exception details somewhere
    
                    // Replace the exception with user friendly message
                    response.HasErrors = true;
                    response.Errors = new Collection<string>();
    
                    response.Errors[0] = exception.Message;
                }
                finally
                {
                    // Clean ups here
                }
    
                return response;
            }
    

    这只是一个例子。您可能需要编写适当的异常处理代码,而不是简单地使用通用 catch 块。

    注意:这只会处理您的应用程序中发生的异常。在客户端和服务之间的通信过程中发生的任何异常,仍然会被抛出到客户端应用程序。

    【讨论】:

    • 感谢您的回答。那么最好的建议方法是找出异常是什么?我可以返回带有 Exception 属性的对象,如果它不为 null,则从它们中拉出异常?
    • 谢谢。有没有更好的方法来做我的 web 服务来解决这个问题只是为了处理异常? WCF 能做得更好吗?
    • 嗯,WCF 是一个不同的野兽。您可以将异常作为 FaultContract 发送给客户端。尽管如此,客户端应用程序仍需要处理它们。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-20
    • 2012-01-01
    • 2011-07-19
    • 2014-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多