使用 FaultException 抛出用户友好的消息

你可以处理异常并抛出一个最友好的消息,例如’Unavailable service’抛出 FaultException:

try
{
    // your service logic here
}
catch (Exception ex)
{
    // You can do something here, like log the original exception
    throw new FaultException("There was a problem processing your request");
}

在你的客户端中,你可以轻松获取消息:

try
{
    // call the service
}
catch (FaultException faultEx)
{
   var errorMessage = faultEx.Message;
   // do something with error message
}

你可以将处理的异常与其他异常区分开来,例如网络错误,在代码中添加其他捕获:

try
{
    // call the service
}
catch (FaultException faultEx)
{
   var errorMessage = faultEx.Message;
   // do something with error message
}
catch (CommunicationException commProblem)
{
    // Handle the communication error, like trying another endpoint service or logging
}