繁体   English   中英

WCF服务调用上的正确错误处理

[英]Proper Error Handling on a WCF service call

我想找出最好的方法来调用WCF服务,并在发生错误或超时时进行处理。 这是我在做什么:

我有一个这样的数据服务接口:

public interface IDataService

{void GetUserId(字符串userName,字符串密码,操作getUserIdComplete); }

我这样实现:

public class MockDataService : IDataService
{
    private Action<string> _getUserIdCompleted;
    private SomeServiceClient;

    public MockDataService()
    {
        _proxy = new SomeServiceClient();
    }

    public void GetUserId(string userName, string password, Action<int> getUserIdComplete)
    {
        _getUserComplete = getUserIdComplete;

        var request = new UserRequest();
        request.UserName = userName;
        request.Password = password;
        //populate any other request info

        _proxy.GetUserIdCompleted += new EventHandler<GetUserCompletedEventArgs>(_proxy_GetUserIdCompleted);
        _proxy.GetUserIdAsync(request);
    }

    void _proxy_GetUserIdCompleted(object sender, GetUserIdCompletedEventArgs e)
    {
        _proxy.GetUserIdCompleted -= new EventHandler<GetUserCompletedEventArgs>(_proxy_GetUserIdCompleted);
        _getUserIdComplete(e.UserId);
    }
}

我的问题是,当发生错误或请求超时时,应用程序将终止。 我可以在电话周围包裹一个try catch块,但这听起来是个坏主意。

有人可以帮我用这种方法优雅地处理超时和错误吗?

据我所知,捕获超时异常是处理它的唯一方法。

我更喜欢使用其他异步模式,因为它在处理异常方面具有更大的灵活性。 我会这样。

public class MockDataService : IDataService
{
    private SomeServiceChannel _channel;

    public MockDataService()
    {
        var channelFactory = new ChannelFactory<SomeServiceChannel>(
                    "CustomBinding_SomeService");
        _channel = channelFactory.CreateChannel();
        //to increase the timeout
        _channel.OperationTimeout = TimeSpan.FromMinutes(5);
    }

    public void GetUserId(string userName, string password, Action<int> getUserIdComplete)
    {
        var request = new UserRequest();
        request.UserName = userName;
        request.Password = password;
        //populate any other request info

        _proxy.GetUserIdCompleted += new EventHandler<GetUserCompletedEventArgs>(_proxy_GetUserIdCompleted);
        _proxy.GetUserIdAsync(request);
        _channel.BeginGetUserId(request, (iar) =>
           {
               try
               {
                   var result = _channel.EndGetUserId(iar);
                   getUserIdComplete(result.UserId);
               }
               catch (Exception ex)
               {
                   //handle the exception
               }
           }, null);
    }

}

以我的拙见,后台线程的回调(任何由异步执行产生的回调)都应始终包装在异常处理程序中。 后台线程中未处理的异常杀死您的进程。

现在,这并不意味着您应该捕获该异常并忽略它:)只是您应该正确处理它,无论这对您的应用程序意味着什么。 对于将要记录它们的某些应用程序。 对于其他人,它将在某处更新某些状态。 对于其他人,它可能会警告用户错误。 或它们的组合:)

暂无
暂无

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

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