开发者

Logging exceptions in WCF with IErrorHandler inside HandleError or ProvideFault?

I'm using IErrorHandler to do exception handling in WCF and now I want to log the exceptions, along with the stack trace and the user that caused the exception.

The only way I can see to get the user that caused the exception is:

OperationContext.Current.IncomingMessageProperties.Security.ServiceSecurityContext.PrimaryIdentity

...But this only seems to work inside ProvideFault, and not inside HandleError. Is there a way to get the user inside HandleError?开发者_如何学运维 I would like to use HandleError instead of ProvideFault as that's called on a background thread and meant for error logging, right?


The two methods of the IErrorHandler have quite well defined responsibilities:

  • HandleError is here to handle all uncaught exceptions - that's why it's the best place to do your logging - that's really its whole reason to be

  • ProvideFault is tasked with turning your .NET exception into an interoperable SOAP fault - or ignore the exception alltogether

Of course, there's nothing technically stopping you from doing your logging in the ProvideFault method - it's just not the place I would go look for that functionality if I ever had to look for it. I tend to like to follow to principle of least surprise - if the method is called ProvideFault, I only expect it to provide a FaultException<T> - not do a lot of other things, too.

To get access to your service's security context, use this snippet of code:

ServiceSecurityContext secCtx = ServiceSecurityContext.Current;

if(secCtx.PrimaryIdentity != null)
{
   // do something with primary identity
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜