使用 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
}