简体   繁体   English

.NET WebService错误处理设计

[英].NET WebService Error Handling Design

I am faced with a design/architectural problem, and can't figure out a clean solution. 我面临设计/架构问题,无法解决一个干净的解决方案。 We have a .NET WebService with hundreds of WebMethods. 我们有一个带有数百种WebMethod的.NET WebService。 (See example below). (请参见下面的示例)。 If any of the called WebMethods throws an unhandled exception, we want to generate an email. 如果任何被调用的WebMethods抛出未处理的异常,我们想生成一封电子邮件。

Question : What would be a clean design pattern to use in such a situation. 问题 :在这种情况下使用哪种干净的设计模式。 I want to avoid inserting repetitive code into hundreds of methods? 我想避免将重复代码插入数百种方法中?

[WebService(Namespace = "http://example.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[Serializable]
public class WebService : System.Web.Services.WebService
{
    [WebMethod]
    public string GetQuoteInfo(string request)
    {
        return QuoteService.GetQuoteInfo(request);
    }

    [WebMethod]
    public string GetQuoteAPR(string request)
    {
        return QuoteService.GetQuoteAPR(request);
    }

    [WebMethod]
    public string GetAccountContactInfo(string request)
    {
        return AccountService.GetAccountContactInfo(request);
    }

    ...
    ...
    ...

    [WebMethod]
    public string GetAccountContactInfo(string request)
    {
        // implementation
    }

} }

  1. Introduce a class that wraps actual method with a try/catch block with proper exception handling. 介绍一个类,该类使用适当的异常处理将带有try / catch块的实际方法包装起来。

     public static class InvocationHelper { public static string SafeInvoke(Func<string, string> f, string request) { try { return f(request); } catch(Exception ex) { NofityAboutException(ex); return null; } } } 
  2. Modify your WebService methods using that class: 使用该类修改WebService方法:

     [WebMethod] public string GetQuoteInfo(string request) { return InvocationHelper.SafeInvoke(r => QuoteService.GetQuoteInfo(r), request); } 

try { 尝试{

your code here in your web method 您的代码在您的网络方法中

    }

    catch (Exception e)
    {

// Email this error message //通过电子邮件发送此错误消息

        e.Message;
        throw;
    }

put it on all your method as there is no way to get perfect error message. 将其放在您的所有方法上,因为无法获取完美的错误消息。 its one time work to get error message and you will be free to debug your code every time. 它的一次性工作将获得错误消息,并且您每次都可以自由调试代码。

One way would be to use an AOP library such as NConcern . 一种方式是使用AOP库,例如NConcern Depending on your scenario it may have some limitations, as the library must be rewritten with CNeptune (see NCover examples). 根据您的方案,它可能会有一些限制,因为必须使用CNeptune重写该库(请参见NCover示例)。

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

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