你如何从Web服务中捕获抛出的SOAP异常?

Lou*_*Lou 12 c# service soap exception

我成功地在我的Web服务中抛出了一些soap异常.我想捕获异常并访问被异常调用的字符串和ClientFaultCode.以下是我在Web服务中的一个例外情况的示例:

throw new SoapException("You lose the game.", SoapException.ClientFaultCode);
Run Code Online (Sandbox Code Playgroud)

在我的客户端,我尝试从可能抛出异常的Web服务运行该方法,并且我抓住了它.问题是我的catch块没有做任何事情.看这个例子:

try
{
     service.StartGame();
}
catch
{
     // missing code goes here
}
Run Code Online (Sandbox Code Playgroud)

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

Ray*_* Lu 11

您可能希望捕获特定的异常.

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
}
Run Code Online (Sandbox Code Playgroud)


Ben*_*n S 7

抓住SoapException实例.这样你就可以访问它的信息:

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

  • 为了确保Lou不会破坏他的代码,他可能会添加一个额外的块`catch(异常e)`.有时异常可能不是`SoapException` ...例如:`OutOfMemoryException`,或连接问题,或线程中止等. (2认同)