我有一个带有自定义 IErrorHandler 的 REST WCF 服务,这样我就可以在我的服务中捕获所有未捕获的异常并返回自定义错误消息、正确的 Http 状态代码 (500) 并记录错误。
问题是 IErrorHandler 将捕获不是源自我的代码的异常,因此如果我使用无效的 JSON 数据对服务进行 POST,我将得到一个 SerializationException。如果不是我的 IErrorHandler,我将像处理所有其他未捕获的异常一样处理它,该异常将被转换为状态代码为 BadRequest 400 的 WebFaultException。
有没有办法处理这些情况,或者我应该在我的 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);
}
}