Logging exceptions in WCF with IErrorHandler inside HandleError or ProvideFault?

こ雲淡風輕ζ 提交于 2020-01-02 04:00:53

问题


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?


回答1:


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
}


来源:https://stackoverflow.com/questions/2869436/logging-exceptions-in-wcf-with-ierrorhandler-inside-handleerror-or-providefault

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!