到目前为止,我一直使用从 javascript 调用的网络服务 ASMX。它一直运行良好,但因为我需要对序列化进行一些控制,所以我正在尝试切换到 DataContracts 和 WCF。 但是,我确实相信我误解了一些东西,因为我试图从客户端代码 (javascript) 中捕获故障异常,但我收到的唯一错误代码是: (翻译,所以可能不准确)
“由于内部错误,服务器无法处理请求。您可以通过激活 IncludeExceptionDetailInFaults 获取有关错误的更多信息...”
我尝试将 IncludeExceptionDetailInFauls 设置为 true,这会提供一些信息,但据我了解,抛出 FaultExceptions 的全部意义在于对用户隐藏异常,并且只抛出一些信息?我正在尝试使用 IErrorHandler,但我有 创建了一个更简单的示例:
SVC:
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class WcfTest
{
// To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json)
// To create an operation that returns XML,
// add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
// and include the following line in the operation body:
// WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
[OperationContract]
public string DoOk()
{
// Add your operation implementation here
return "Success";
}
[OperationContract]
public string DoFail()
{
FaultReason reason = new FaultReason("Fail <- This is good :)");
throw new FaultException(reason);
return "Success";
}
}
包含在脚本管理器中,并由以下 javascript 调用:
<a href="java script:void(0);" onclick="DoOk()">OK</a><br />
<a href="java script:void(0);" onclick="DoFail()">Fail</a>
<script>
function DoOk() {
WcfTest.DoOk(
function (result) {
alert("DoOk Success: "+result);
},
function (result) {
alert("DoOk Failed: " + result);
})
}
function DoFail() {
WcfTest.DoFail(
function (result) {
alert("DoFail Success: " + result);
},
function (result) {
alert("DoFail Failed: " + result);
})
}
</script>
和服务模型:
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="WcfTestAspNetAjaxBehavior">
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="WcfTestAspNetAjaxBehavior">
<enableWebScript />
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
<services>
<service name="WcfTest">
<endpoint address="" behaviorConfiguration="WcfTestAspNetAjaxBehavior"
binding="webHttpBinding" contract="WcfTest" />
</service>
</services>
</system.serviceModel>
我还尝试使用以下组合来标记 DoFail 方法:
[FaultContract(typeof(FaultException))]
[FaultContract(typeof(FaultReason))]
我是不是误会了什么?您是否应该能够通过抛出 FaultException
而不必将 IncludeExceptionDetailInFaults
设置为 true 来获取异常信息?
最佳答案
有用的资源:
主要步骤:
- 通过实现 IErrorHandler 接口(interface)创建您自己的错误处理程序
- 创建 WebHttpBehavior 的子类并将默认错误处理程序替换为您自己的错误处理程序
- 通过使用自定义 ServiceHostFactory 或在 web.config 中定义为 behaviorExtension 来插入您的自定义/扩展行为
关于javascript - 无法从故障异常中获取信息(javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6563736/