【问题标题】:Handle exceptions in web services with Elmah使用 Elmah 处理 Web 服务中的异常
【发布时间】:2011-01-11 22:06:11
【问题描述】:

有没有办法像我们在 ASP.NET 网站中那样使用 ELMAH 来全局处理常规 ASP.NET Web 服务 (asmx) 中的异常?

【问题讨论】:

    标签: asp.net web-services asmx elmah


    【解决方案1】:

    ASP.NET Web 服务永远不会触发 Application_Error 事件,ELMAH 无法像在 ASP.NET 应用程序中那样全局处理异常。但是我们可以使用 ELMAH“手动”记录异常:

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

    【讨论】:

    • 这就是我的想法,但我正在检查是否有“更清洁”的解决方案。谢谢
    • 是的,更清洁的解决方案或实践对我来说也会很有趣。这是个好问题 (+1)。
    • 我终于使用了您的解决方案,但没有找到更好的方法。感谢您的提示。
    • 使用 Elmah.ErrorSignal.FromCurrentContext().Raise(ex);而是触发所有订阅/配置的日志类型/过滤器
    • FromCurrentContext() 是更好的解决方案,我在 2012 年 2 月 22 日发布了针对该影响的答案。由于某种原因,它在同一天被删除。如果有任何高级用户碰巧访问,请检查我的回答,如果您认为合适,请投票支持取消删除。
    【解决方案2】:

    您可以使用 SoapExtension 来执行此操作:

    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
                }
            }
        }
    }
    

    您在 web.config 中使用以下行进行注册:

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

    这将使您能够访问 HttpContext 和 SoapMessage 对象,它们应该为您提供有关被调用内容的所有详细信息。我认为您在此阶段检索到的异常将始终是 SoapException,而您感兴趣的部分可能是内部异常。

    【讨论】:

    • 还没有机会尝试这个,但它看起来应该可以工作。如果它说“在此处记录异常”,则代码 Elmah.ErrorLog.GetDefault( HttpContext.Current).Log(new Elmah.Error(ex, HttpContext.Current)); 可能会起作用。
    • @DavidRobbins 不,但我看不出有什么理由不一样。
    • 不幸的是,这种方法不适用于 ScriptService/JSON (stackoverflow.com/a/9585721/198065)
    • group="1" 有效吗? Intellisense 建议您需要“低”或“高”。
    • 也许我错过了重点,但我认为这仅适用于调用另一个 Web 服务,不适用于我的内部未处理错误
    【解决方案3】:

    您可以使用此代码

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

    【讨论】:

      猜你喜欢
      • 2011-12-05
      • 1970-01-01
      • 1970-01-01
      • 2014-12-31
      • 1970-01-01
      • 2018-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多