将WCF异常返回给Silverlight客户端的最佳做法是什么?

时间:2013-01-17 17:30:34

标签: c# .net wcf silverlight exception

我相信标题说我想知道的。在大多数情况下,WCF服务返回NotFound异常,即使我在服务中处理异常,它也会返回一些等等,这很难实现完全异常。我想知道是否有任何干净和好的方法可以将确切的WCF异常返回给Silverlight客户端?

1 个答案:

答案 0 :(得分:2)

好的,这就是你应该做的:

public App()
{
    ...
    this.UnhandledException += this.Application_UnhandledException;
    ...
}

private void Application_UnhandledException(object sender, 
        ApplicationUnhandledExceptionEventArgs e)
{
    if(e.Exception is YourException){
        //show a message box or whatever you need
        e.Handled = true; //if you don't want to propagate
    }
}

修改

WPF

public App()
{
    this.Dispatcher.UnhandledException += 
        new System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(
            Dispatcher_UnhandledException);
}

void Dispatcher_UnhandledException(object sender, 
    System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
    if(e.Exception is YourException){
        //show a message box or whatever you need
        e.Handled = true; //if you don't want to propagate
    }
}

您可以检查错误属性,如下所示:Best way to catch a WCF exception in Silverlight?

或者您可以在Behavior课程中添加ServiceHost

public ServiceHost(Type t, params Uri[] baseAddresses) :
            base(t, baseAddresses) { }

protected override void OnOpening()
{
    base.OnOpening();

    //adding the extra behavior
    this.Description.Behaviors.Add(new ExceptionManager());

然后您创建一个名为ExceptionManager的类,如下所示:

public sealed class ExceptionManager : IServiceBehavior, IErrorHandler

然后是一个名为ProvideFault的方法,如下所示:

void IErrorHandler.ProvideFault(Exception error, MessageVersion version, 
    ref Message fault)
{
    if (error == null)
        throw new ArgumentNullException("error");

    Fault customFault = new Fault();

    customFault.Message = error.Message

    FaultException<Fault> faultException = new FaultException<Fault>(customFault,
        customFault.Message, new FaultCode("SystemFault"));
    MessageFault messageFault = faultException.CreateMessageFault();
    fault = Message.CreateMessage(version, messageFault, faultException.Action);
}

使用ServiceHost

创建课程ServiceHostFactory

public class ServiceHostFactory : 
    System.ServiceModel.Activation.ServiceHostFactory
{
    protected override System.ServiceModel.ServiceHost CreateServiceHost(Type t, 
        Uri[] baseAddresses)
    {
        return new ServiceHost(t, baseAddresses);
    }
}

右键点击您的服务,选择View Markup并添加标记:

Factory="YourNamespace.ServiceHostFactory"