1

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

4

1 回答 1

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

您可以检查错误属性,如下所述:在 Silverlight 中捕获 WCF 异常的最佳方法?

或者,您可以在班级中添加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" 
于 2013-01-17T17:57:35.967 回答