简体   繁体   English

WCF完成事件中的异常处理

[英]Exception Handling in WCF's Completed Event

I am wondering how to catch Exception in my WCF's completed event method and show it to the User in the MessageBox . 我想知道如何在WCF's完成的事件方法中捕获Exception,并在MessageBox中将其显示给User。

I call the GetProductTypeAsync(); 我叫GetProductTypeAsync(); method that fetches records from the Database. 从数据库中获取记录的方法。 I want to catch any Exception that occurs here and send it to the service_GetProductTypeCompleted Event where it should show the Exception Message to the User. 我想捕获此处发生的任何异常,并将其发送到service_GetProductTypeCompleted事件,在该事件中应向用户显示Exception Message

public List<ProductType> GetProductType()
{
    List<ProductType> productType = new List<ProductType>();
    try
    {
        using (SqlConnection con = new SqlConnection(_connectionString))
        {
            SqlCommand cmd = new SqlCommand("usp_Get_ProductType", con);
            cmd.CommandType = CommandType.StoredProcedure;
            con.Open();
            using (SqlDataReader reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    ProductType pType = new ProductType(Convert.ToInt32(reader["pkProductTypeID"]), reader["Name"].ToString());
                    productType.Add(pType);
                }
            }
        }
    }
    catch(Exception ex)
    {
        //Catch Exception and send to the service_GetProductTypeCompleted Event Method
    }
    return productType;
} 

Here is the service_GetProductTypeCompleted Event 这是service_GetProductTypeCompleted事件

void service_GetProductTypeCompleted(object sender, GetProductTypeCompletedEventArgs e)
{
    if (e.Result.Count != 0)
    {
        productTypes = e.Result.ToList();
        cboProductType.DataContext = productTypes;
    }
}

When you send an exception from your service , the client would receive generic error message: 当您从服务发送exception ,客户端将收到通用错误消息:

The server was unable to process the request due to an internal error. 由于内部错误,服务器无法处理请求。 For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework SDK documentation and inspect the server trace logs." 有关错误的更多信息,请打开服务器上的IncludeExceptionDetailInFaults(从ServiceBehaviorAttribute或从配置行为),以便将异常信息发送回客户端,或者按照Microsoft .NET Framework SDK文档和检查服务器跟踪日志。”

If you want to catch the specific exception on the client side, then you should throw what is called FaultException from the service . 如果要在客户端捕获特定的异常 ,则应该从service抛出所谓的FaultException These are Soap Faults and can be recognized by any consumers . 这些是肥皂故障 ,任何消费者都可以识别。 Please note that your consumers for your service is not always .NET consumer, so throwing CLR exception wouldn't be recognized. 请注意,您使用服务的使用者并不总是.NET使用者,因此不会识别抛出CLR异常。 That's the reason why you need to throw Soap exception . 这就是为什么您需要throw Soap exception的原因。

Eg this is how you would catch and throw Fault Exception 例如,这就是您捕获并抛出Fault Exception

catch (FaultException<AnyTypeThatCanBeSerialized> ex)
        {
            throw;
        }

Read this article for more details on wcf Faults 阅读本文以获取有关wcf Faults更多详细信息

The FaultException does not flow to Silverlight. FaultException不会流到Silverlight。 You will need to return a class similar to the following from your service layer: 您将需要从服务层返回类似于以下内容的类:

public class ServiceReturnInformation<T>
{
    public T DataContext { get; set; }

    private IList<string> _warnings;
    public IList<string> Warnings
    {
        get { return _warnings ?? (_warnings = new List<string>()); }
        set { _warnings = value; }
    }

    private IList<string> _errors;
    public IList<string> Errors
    {
        get { return _errors ?? (_errors = new List<string>()); }
        set { _errors = value; }
    }
}  

If an exception occurs, your service needs to catch the exception and set the Errors/Warnings properties. 如果发生异常,则您的服务需要捕获该异常并设置Errors / Warnings属性。

    var result = new ServiceReturnInformation<Employee>();
    try
    {
        // Do something
        result.DataContext = GetEmployee();
    }
    catch (Exception ex)
    {
        result.DataContext = null;
        result.Errors.Add(ex.Message);
    }

    return result;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM