C# 如何从 Web 服务中捕获抛出的soap异常?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1805345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 21:00:07  来源:igfitidea点击:

How do you catch a thrown soap exception from a web service?

c#soapserviceexception

提问by Lou

I throw a few soap exceptions in my web service successfully. I would like to catch the exceptions and access the string and ClientFaultCode that are called with the exception. Here is an example of one of my exceptions in the web service:

我成功地在我的网络服务中抛出了一些肥皂异常。我想捕获异常并访问使用异常调用的字符串和 ClientFaultCode。以下是我在 Web 服务中的例外之一的示例:

throw new SoapException("You lose the game.", SoapException.ClientFaultCode);

In my client, I try to run the method from the web service that may throw an exception, and I catch it. The problem is that my catch blocks don't do anything. See this example:

在我的客户端中,我尝试从可能引发异常的 Web 服务运行该方法,并捕获它。问题是我的 catch 块没有做任何事情。看这个例子:

try
{
     service.StartGame();
}
catch
{
     // missing code goes here
}

How can I access the string and ClientFaultCode that are called with the thrown exception?

如何访问使用抛出的异常调用的字符串和 ClientFaultCode?

采纳答案by Ben S

Catch the SoapExceptioninstance. That way you can access its information:

抓住SoapException实例。这样您就可以访问其信息:

try {
     service.StartGame();
} catch (SoapException e)  {
    // The variable 'e' can access the exception's information.
}

回答by CaffGeek

catch (SoapException soapEx) 
{
  //Do something with soapEx
}

回答by Ray Lu

You may want to catch the specific exceptions.

您可能想要捕获特定的异常。

try
{
     service.StartGame();
}
catch(SoapHeaderException)
{
// soap fault in the header e.g. auth failed
}
catch(SoapException x)
{
// general soap fault  and details in x.Message
}
catch(WebException)
{
// e.g. internet is down
}
catch(Exception)
{
// handles everything else
}