如何在库类项目中序列化异常?

时间:2019-06-07 09:25:03

标签: c# exception serialization dynamics-crm libphonenumber

我想在我的CRM Dynamics插件中使用Google提供的PhoneNumbers库。

我的插件尝试解析电话号码。 执行时,我得到以下执行:

  

System.Runtime.Serialization.SerializationException:成员'PhoneNumbers.NumberParseException,aug.R2BCore.Crm.Plugins的类型未解析

异常类缺少序列化属性,我添加了它。

这是异常类的代码:


namespace PhoneNumbers
{
    public enum ErrorType
    {
        INVALID_COUNTRY_CODE,
        // This generally indicates the string passed in had less than 3 digits in it. More
        // specifically, the number failed to match the regular expression VALID_PHONE_NUMBER in
        // PhoneNumberUtil.java.
        NOT_A_NUMBER,
        // This indicates the string started with an international dialing prefix, but after this was
        // stripped from the number, had less digits than any valid phone number (including country
        // code) could have.
        TOO_SHORT_AFTER_IDD,
        // This indicates the string, after any country code has been stripped, had less digits than any
        // valid phone number could have.
        TOO_SHORT_NSN,
        // This indicates the string had more digits than any valid phone number could have.
        TOO_LONG
    }

    [Serializable] // added 
    public class NumberParseException : Exception
    {
        public readonly ErrorType ErrorType;

        public NumberParseException(ErrorType errorType, string message) :
            base(message)
        {
            ErrorType = errorType;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

插件在单独的应用程序域上下文中运行。当您引发异常时,该异常会传播到在不同应用程序域中执行的SandboxExecutionWorkerProcess,然后您的插件就会出现并且不知道您的自定义展示类型。因此,无论您如何序列化异常,该类型都必须在另一端反序列化。

我建议采用以下方法(例外包装):

public abstract class BasePlugin : IPlugin {
  protected abstract DoExecute(IServiceProvider serviceProvider);
  public void Execute(IServiceProvider serviceProvider) {
    try { 
      this.DoExecute(serviceProvider); 
    } catch (Exception e) {
      throw new InvalidPluginExecutionException(e.ToString());
    }
  }
}

如果您有一组固定的自定义异常类型,则可以增强此代码以仅处理这些异常类型。还请注意,这样做会向CRM用户公开堆栈跟踪信息-如果您仅为公司开发插件,那很好,但是如果您是ISV,则应考虑将其隐藏。