将WCF异常返回到Silverlight客户端的最佳实践是什么?
本文关键字:最佳 是什么 客户端 异常 WCF 返回 Silverlight | 更新日期: 2023-09-27 17:53:54
我相信标题说明了我想知道的。在大多数情况下,WCF服务返回NotFound
异常,即使我在服务中处理异常,它也会返回一些乱七八糟的东西,很难意识到确切的异常是什么。我想知道是否有任何干净和好的方法来返回确切的WCF异常到Silverlight客户端?
好的,你应该这样做:
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
}
}
你可以检查error属性,如下所述:在Silverlight中捕获WCF异常的最佳方法?
或者您可以在ServiceHost
类中添加Behavior
。
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"