3

私のWebアプリケーションでは、global.asaxのApplication_Error関数を使用して、次のようなすべての例外をログに記録します。

void Application_Error(object sender, EventArgs e)
{
    Exception ex = Server.GetLastError();

    while (ex.GetBaseException() != null)
    {
        ex = ex.GetBaseException();
    }

    log.writeError(ex.ToString());
}

運が悪かったので、WCFRESTサービスで同様のことを試しました。グローバルエラー処理を追加するにはどうすればよいですか?この記事を見ましたが、IServiceBehaviorの実装は初めてです。上記のコードはどこに追加しますか?

4

1 に答える 1

7

私が使う:

1)AppDomain.CurrentDomain.UnhandledExceptionイベント

2)TaskScheduler.UnobservedTaskExceptionイベント

3)IErrorHandler:

    public class ErrorHandler : IErrorHandler
    {
        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {
            var faultException = new FaultException<string>("Server error: " + error.Format());
            var messageFault = faultException.CreateMessageFault();
            fault = Message.CreateMessage(version, messageFault, null);
        }

        public bool HandleError(Exception error)
        {
            return false;
            //return true; //if handled
        }
    }

[AttributeUsage(AttributeTargets.Class)]
public class ErrorHandlerBehavior : Attribute, IEndpointBehavior, IServiceBehavior
{
    public void Validate(ServiceEndpoint endpoint)
    {

    }

    public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
    {

    }

    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
    {
        endpointDispatcher.ChannelDispatcher.ErrorHandlers.Add(new ErrorHandler()); 
    }

    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {

    }

    public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {

    }

    public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
    {

    }

    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
        foreach (ChannelDispatcher channelDispatcher in serviceHostBase.ChannelDispatchers)
        {
            channelDispatcher.ErrorHandlers.Add(new ErrorHandler());
        }
    }
}

これは、サービスimpl全体に適用できます。クラス:

[ErrorHandlerBehavior]
    public class SubscriberInfoTaskService : {}

またはエンドポイントへ:

var endpoint = Host.Description.Endpoints.FirstOrDefault();

//foreach (ChannelDispatcher channelDispatcher in Host.ChannelDispatchers) //ChannelDispatcherBase
//{                 
//    channelDispatcher.ErrorHandlers.Add(new ErrorHandler());
//}

endpoint.Behaviors.Add(new ErrorHandlerBehavior());

構成の使用についてはこちら:http://www.steverb.com/post/2008/11/24/Useful-WCF-Behaviors-IErrorHandler.aspx

于 2013-02-28T14:31:24.800 に答える