简体   繁体   English

实现WCF IErrorHandler仅用于日志记录

[英]Implementing WCF IErrorHandler for logging only

Probably trivial question.. I want to implement my own error handler to log errors and monitor what's going on. 可能是微不足道的问题..我想实现我自己的错误处理程序来记录错误并监视正在发生的事情。 At this point I don't want to provide my own faults to the clients. 此时我不想向客户提供自己的错误。 I want it to be transparent - just like default WCF behavior. 我希望它是透明的 - 就像默认的WCF行为一样。 How should I implement ProvideFault to achieve this? 我应该如何实现ProvideFault来实现这一目标?

namespace IDATT.Web.Services
{
    using System;
    using System.ServiceModel.Channels;
    using System.ServiceModel.Dispatcher;

    public class MyServiceErrorHandler : IErrorHandler 
    {
        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            // ????
        }

        public bool HandleError(Exception error)
        {
            return true;
        }
    }
}

You can leave it empty. 你可以把它留空。 I do this to log errors to Elmah with no issues. 我这样做是为了将错误记录到Elmah而没有任何问题。

EDIT 编辑

I'm completely wrong on this. 我对此完全错了。 After looking at my implementation I do the following. 在查看我的实现后,我执行以下操作。 As you can see, HandleError is the method that is basically empty and the logging takes place in ProvideFault . 如您所见, HandleError是基本上为空的方法,日志记录发生在ProvideFault

public class ElmahErrorHandler : IErrorHandler
{
    public bool HandleError(Exception error)
    {
        return false;
    }


    public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
    {
        if (error == null)
        {
            return;
        }

        ErrorSignal.FromCurrentContext().Raise(error);
    }
}

Returning true in HandleError will make WCF think that no error occured. HandleError返回true将使WCF认为没有发生错误。 That means if you are just logging the error, this should always return false . 这意味着如果您只记录错误,则应始终返回false If the error is not handled, ProvideFault is called and this is where you want to do the logging. 如果未处理错误,则调用ProvideFault ,这是您要进行日志记录的位置。 You do not need to provide a fault Message. 您不需要提供故障消息。

From the documentation ( http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.ierrorhandler.aspx ): 从文档( http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.ierrorhandler.aspx ):

Implement the HandleError method to ensure error-related behaviors, including error logging, assuring a fail fast, shutting down the application, and so on. 实现HandleError方法以确保与错误相关的行为,包括错误记录,确保快速失败,关闭应用程序等。

Also the link above notes that only HandleError is called after the response has been sent back to the client. 此外,上面的链接指出, 将响应发送回客户端之后 ,仅调用HandleError。 So be nice to your client (don't make them wait while you log), leave ProvideFault blank and perform logging operations in HandleError. 因此,对您的客户端要好(不要让他们在您登录时等待),将ProvideFault留空并在HandleError中执行日志记录操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM