【发布时间】:2011-07-18 08:37:33
【问题描述】:
我有一个带有自定义 IErrorHandler 的 REST WCF 服务,这样我就可以在我的服务中捕获所有未捕获的异常并返回自定义错误消息、正确的 Http 状态代码 (500) 并记录错误。
问题在于 IErrorHandler 将捕获不是源自我的代码的异常,因此,例如,如果我使用无效的 JSON 数据对服务进行 POST,我将得到一个 SerializationException。如果不是我的 IErrorHandler,我会像处理所有其他未捕获的异常一样处理它。
有没有办法处理这些情况,或者我应该在我的 IErrorHandler 中捕获 SerializationExceptions 并在那里设置 BadRequest?还有哪些其他异常可能来自 WCF 堆栈而不来自我的代码?
更新:添加了我的 IErrorHandler.ProvideFault 实现
public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
Guid loggingId = Guid.NewGuid();
error.Data["ExceptionLoggingId"] = loggingId;
if (error is SecurityTokenException)
{
fault = Message.CreateMessage(version, string.Empty, String.Format("{0}. The error identifier is {1}", error.Message, loggingId), new DataContractJsonSerializer(typeof(string)));
fault.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Json));
webOperationContextWrapper.SetOutgoingResponseStatusCode(HttpStatusCode.Unauthorized);
}
else
{
if (error is SerializationException)
{
// TODO: What if the SerializationException originates from within the service?
// SerializationException due to malformed JSON
return;
}
fault = Message.CreateMessage(version, string.Empty, String.Format("An unknown error has occurred. The error identifier is {0}", loggingId), new DataContractJsonSerializer(typeof(string)));
fault.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Json));
webOperationContextWrapper.SetOutgoingResponseStatusCode(HttpStatusCode.InternalServerError);
}
}
【问题讨论】:
-
如果您没有在 ProvideFault 中分配故障消息会怎样?
-
然后它按预期工作;客户端将收到 http 状态码 400。但这意味着我在 IErrorHandler 中检查 SerializationExceptions。但是如果那个 SerializationException 来自我的服务而不是来自 WCF 堆栈,那么它是一个服务器错误(我做的一些序列化出错了),我想返回状态码 500。你看到问题了吗?跨度>
-
我添加了我的实现来阐明我的意思
-
我认为您需要处理服务代码中的异常并将其转换为其他内容才能正常工作
-
是的,我实现 IErrorHandler 的原因是为了避免对我在服务中所做的所有事情进行一般性尝试捕获,但也许这是一个更好的解决方案?
标签: .net wcf rest ierrorhandler