我有一个带有自定义IErrorHandler的REST WCF服务,这样我就可以捕获服务中所有未察觉的异常,并返回一个自定义错误消息,一个正确的Http状态代码(500)并记录错误。
问题是,IErrorHandler将捕获并非源自我的代码的异常,因此,如果我使用无效的JSON数据向服务发送一篇文章,我将得到一个SerializationException。如果不是针对我的WebFaultException,该异常将被转换为一个状态代码BadRequest 400的IErrorHandler,在那里,我将像处理所有其他未处理的异常一样处理它。
是否有一种处理这些情况的方法,还是应该在IErrorHandler中捕获IErrorHandler并在那里设置BadRequest?如果没有我的代码,orginate可能会从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);
}
}发布于 2011-11-07 20:17:51
我遇到了一个类似的问题。
我的解决方案是使用命名空间来确定异常的起源。
if (!error.StackTrace.TrimStart().StartsWith("at " + this.GetType().Namespace.Split('.')[0]))
return;这在我目前的项目中是可行的。但取决于你的计划它可能不会..。
发布于 2012-08-29 20:48:11
我认为@RichardBlewett是对的。您将希望创建一个自定义异常类并将其抛出,在错误处理程序中检查该类型,然后让标准的序列化异常正常地通过。对我来说,这似乎是最好的设计模式。
然后,您将得到一个类型安全异常,如果删除或更改,错误处理程序代码将不会编译,如果通过VS执行,则会与该类型重构。像这样测试名称空间可能不太可取(尽管非常聪明),因为它在编译时不直接与任何类型绑定。如果您在周围更改名称空间,就会遇到一个很难跟踪的问题。
https://stackoverflow.com/questions/6730398
复制相似问题