Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle exceptions in web services with Elmah

Is there a way to globally handle exceptions in regular ASP.NET Web Service (asmx) using ELMAH like we do it in ASP.NET web site ?

like image 607
mberube.Net Avatar asked Feb 01 '10 21:02

mberube.Net


People also ask

What is the use of ELMAH?

ELMAH enables logging of all unhandled exceptions. ELMAH logs all errors in many storages, like - SQL Server, MySQL, Randon Access Memory (RAM), SQL Lite, and Oracle. ELMAH has functionality to download all errors in CSV file.

What does ELMAH stand for?

ELMAH (Error Logging Modules and Handlers) is an open-source debugging tool for ASP.NET web services. When added to a running web application on a machine, exceptions that are thrown trigger event handlers in the ELMAH tool.


2 Answers

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));   } }  
like image 160
Tadas Šukys Avatar answered Oct 02 '22 16:10

Tadas Šukys


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.

like image 28
Liam Corner Avatar answered Oct 02 '22 17:10

Liam Corner