Handle exceptions in web services with Elmah

孤街醉人 提交于 2019-11-27 21:02:56
Tadas Šukys

ASP.NET web services never fire Application_Error event and exceptions cannot be handled globally by ELMAH like in ASP.NET apps. But we can "manually" log exceptions using ELMAH:


public int WebServiceMethod() {
  try {
   ...
  }
  catch (Exception ex) {
    Elmah.ErrorLog.GetDefault(
      HttpContext.Current).Log(new Elmah.Error(ex, HttpContext.Current));
  }
}

You can use a SoapExtension to do this :

using System;
using System.Web.Services.Protocols;

namespace MyNamespace
{
    class ELMAHExtension : SoapExtension
    {
        public override object GetInitializer(Type serviceType)
        { return null; }

        public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute)
        { return null; }

        public override void Initialize(object initializer)
        { }

        public override void ProcessMessage(SoapMessage message)
        {
            if (message.Stage == SoapMessageStage.AfterSerialize &&
                message.Exception != null)
            {
                // Log exception here
            }
        }
    }
}

You register this in the web.config with the following lines :

<system.web>
  <webServices>
    <soapExtensionTypes>
      <add type="MyNamespace.ELMAHExtension, MyDLL" priority="1" group="1" />
    </soapExtensionTypes>
  </webServices>
</system.web>

This will give you access to the HttpContext and SoapMessage objects which should give you all of the details you need about what was being called. I think the exception you retrieve at this stage will always be a SoapException and that the bit you are interested in is probably the inner exception.

You can use this code

 try{
// your code in here
}
     catch (Exception ert)
            {
                Elmah.ErrorSignal.FromCurrentContext().Raise(ert);

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