0

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

我看过这篇文章,但它似乎没有显示如何获取服务引发的异常。

我可以提取 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!");
    }

这可能吗?

4

1 回答 1

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

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

于 2012-07-17T02:45:23.570 回答