gpt4 book ai didi

c# WCF 捕获基本类型的错误异常

转载 作者:太空狗 更新时间:2023-10-29 21:30:47 25 4
gpt4 key购买 nike

我到处寻找如何在 C# 中捕获基本错误契约类型。我想让我所有的错误契约都继承自一个类,并在 MVC Controller 中有一个 catch(FaultException fex)。

数据合约

[DataContract]
public class BaseClass1
{ }

[DataContract]
public class Class2 : BaseClass1
{ }

服务

[ServiceContract]
public interface IService1
{
[OperationContract]
[FaultContract(typeof(BaseClass1))]
[FaultContract(typeof(Class2))] //Do I need this one?
void ThrowClass2();
}

public class Service1 : IService1
{
public void ThrowClass2()
{
throw new FaultException<Class2>(new Class2(), "Class2 Reason");
}
}

服务消费者

FaultTestService.Service1Client client = null;
try
{
client = new FaultTestService.Service1Client();
client.ThrowAmpFaults("InvalidParameter", 0);
}
catch (FaultException<Namespace.BaseClass1> fex)
{
//DOES NOT GO IN HERE AS I WOULD EXPECT
}
catch (FaultException fex)
{
//Other Possible Option
MessageFault fault = fex.CreateMessageFault();
var fe1 = fault.GetDetail<BaseClass1>();
//This throws a serialization exception it needs <Class2>
}

请让我知道是否可以修复这些 catch 语句中的任何一个来完成我正在寻找的事情。

最佳答案

该语法在 C# 中不起作用。请考虑以下“解决方法”。

try
{
throw new FaultException<DerivedClass2>(new DerivedClass2());
}
catch (FaultException fex)
{
bool handled = false;
Type fexType = fex.GetType();
if (fexType.IsGenericType && fexType.GetGenericTypeDefinition() == typeof(FaultException<>))
{
if (typeof(BaseClass1).IsAssignableFrom(fexType.GetGenericArguments()[0]))
{
object detail = fexType.GetProperty("Detail").GetValue(fex, null);

// Use detail here.

handled = true;
}
}

if (!handled)
throw; // Don't know how to handle. Re-throw.
}

如果我们忽略 Detail == null 的不寻常情况,这可以简化但构造的泛型类型匹配。我还将使用 C# 动态关键字进一步简化它。

try
{
throw new FaultException<DerivedClass2>(new DerivedClass2());
}
catch (FaultException fex)
{
bool handled = false;
Type fexType = fex.GetType();
if (fexType.IsGenericType && fexType.GetGenericTypeDefinition() == typeof(FaultException<>))
{
object detail = ((dynamic)fex).Detail;
if (detail is BaseClass1) // true for subclasses too!
{
// Use detail here.
}

}

if (!handled)
throw; // Don't know how to handle. Re-throw.
}

要考虑的另一件事是您是否应该只使用 throw new FaultException<BaseClass1>(new DerivedClass2()) .这种抛出方式可以让您使用最初提供的代码进行捕获。

关于c# WCF 捕获基本类型的错误异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4140030/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com