如何将System.Exception转换为FaultException

时间:2016-02-09 11:51:45

标签: c# wcf exception-handling

我有以下异步调用的方法。我想知道如何将System Exception(我在SQL操作期间可能遇到的)转换为FaultException

以下是方法:

public List<Product> GetProductDetails(int productKey)
{
    try
    {
        using (SqlConnection con = new SqlConnection(_connectionString))
        {
            SqlCommand cmd = new SqlCommand("usp_Get_ProductDetails", con);
            ........
            using (SqlDataReader reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    ......
                }
            }
        }
    }
    catch(Exception ex) 
    {
        //How can I convert this Exception ex into FaultException and then throw to client?
        //throw new FaultException(new FaultReason(new FaultReasonText()), new FaultCode());

    }
}

2 个答案:

答案 0 :(得分:1)

您可以捕获多个异常(事实上,如果合理地可能发生特定异常,这样做是很好的做法),然后对每个异常做一些事情。

例如:

try
{
    using (SqlConnection con = new SqlConnection(_connectionString))
    {
        SqlCommand cmd = new SqlCommand("usp_Get_ProductDetails", con);
        .....
    }
}
catch(FaultException faultEx)
{
    // code to send to client
}
catch(Exception ex) 
{
    // code to do something else
}

答案 1 :(得分:1)

catch(Exception ex) 
{
    throw new FaultException(ex.Message);
}