gpt4 book ai didi

c# - wcf FaultException 原因

转载 作者:行者123 更新时间:2023-11-30 14:11:12 24 4
gpt4 key购买 nike

对于以下异常,没有在异常窗口中指定原因(->查看详细信息):

System.ServiceModel.FaultException The creator of this fault did not specify a Reason. How can I change it to show the reason? (I need 1234 to be shown there)

public class MysFaultException
{
public string Reason1
{
get;
set;
}
}

MyFaultException connEx = new MyFaultException();
connEx.Reason1 = "1234";
throw new FaultException<OrdersFaultException>(connEx);

最佳答案

同时 I3arnon answer如果您希望将所有异常转发给调用者,这很好,如果您只想通过一组有限的已知故障,则可以创建 Fault Contracts这让调用者知道可能会出现一组特定的异常,以便客户端可以准备好处理它们。这允许您传递潜在的预期异常,而无需将您的软件可能抛出的所有异常转发给客户端。

这是 MSDN 中的一个简单示例,它显示了 WCF 服务捕获 DivideByZeroException 并将其转换为 FaultException 以传递给客户端。

[ServiceContract(Namespace="http://Microsoft.ServiceModel.Samples")]
public interface ICalculator
{
//... (Snip) ...

[OperationContract]
[FaultContract(typeof(MathFault))]
int Divide(int n1, int n2);
}

[DataContract(Namespace="http://Microsoft.ServiceModel.Samples")]
public class MathFault
{
private string operation;
private string problemType;

[DataMember]
public string Operation
{
get { return operation; }
set { operation = value; }
}

[DataMember]
public string ProblemType
{
get { return problemType; }
set { problemType = value; }
}
}

//Server side function
public int Divide(int n1, int n2)
{
try
{
return n1 / n2;
}
catch (DivideByZeroException)
{
MathFault mf = new MathFault();
mf.operation = "division";
mf.problemType = "divide by zero";
throw new FaultException<MathFault>(mf);
}
}

关于c# - wcf FaultException 原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20954915/

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