如何正确实现一个自定义可序列化的 Exception

最近在公司的项目中,编写了几个自定义的 Exception 类。提交 PR 的时候,sonarqube 提示这几个自定义异常不符合 ISerializable patten. 花了点时间稍微研究了一下,把这个问题解了。今天在此记录一下,可能大家都会帮助到大家。

自定义异常#

编写一个自定义的异常,继承自 Exception,其中定义一个 ErrorCode 来存储异常编号。平平无奇的一个类,太常见了。大家觉得有没有什么问题?

    [Serializable]
    public class MyException : Exception
    {
        public string ErrorCode { get;}

        public MyException(string message, string errorCode) : base(message)
        {
            ErrorCode = errorCode;
        }
    }

如我们对这个异常编写一个简单的单元测试。步骤如下:

        [TestMethod()]
        public void MyExceptionTest()
        {
            // arrange
            var orignalException = new MyException("Hi", "1000");
            var bf = new BinaryFormatter();
            var ms = new MemoryStream();

            // act
            bf.Serialize(ms, orignalException);
            ms.Seek(0, 0);
            var newException = bf.Deserialize(ms) as MyException;

            // assert
            Assert.AreEqual(orignalException.Message, newException.Message);
            Assert.AreEqual(orignalException.ErrorCode, newException.ErrorCode);
        }

这个测试主要是对一个 MyException 的实例使用 BinaryFormatter 进行序列化,然后反序列化成一个新的对象。将新旧两个对象的 ErrorCodeMessage 字段进行断言,也很简单。
让我们运行一下这个测试,很可惜失败了。测试用例直接抛了一个异常,大概是说找不到序列化构造器。

Designing Custom Exceptions Guideline#

简单的搜索了一下,发现微软有对于自定义 Exception 的
Designing Custom Exceptions

总结一下大概有以下几点:

  • 一定要从 System.Exception 或其他常见基本异常之一派生异常。

  • 异常类名称一定要以后缀 Exception 结尾。

  • 应使异常可序列化。 异常必须可序列化才能跨越应用程序域和远程处理边界正确工作。

  • 一定要在所有异常上都提供(至少是这样)下列常见构造函数。 确保参数的名称和类型与在下面的代码示例中使用的那些相同。

public class NewException : BaseException, ISerializable
{
    public NewException()
    {
        // Add implementation.
    }
    public NewException(string message)
    {
        // Add implementation.
    }
    public NewException(string message, Exception inner)
    {
        // Add implementation.
    }

    // This constructor is needed for serialization.
   protected NewException(SerializationInfo info, StreamingContext context)
   {
        // Add implementation.
   }
}

按照上面的 guideline 重新改一下我们的 MyException,主要是添加了几个构造器。修改后的代码如下:

    [Serializable]
    public class MyException : Exception
    {
        public string ErrorCode { get; }

        public MyException()
        {
        }

        public MyException(string message, string errorCode) : base(message)
        {
            ErrorCode = errorCode;
        }

        public MyException(string message, Exception inner): base(message, inner)
        {
        }

        protected MyException(SerializationInfo info, StreamingContext context)
        {
        }

    }

很可惜按照微软的 guideline 单元测试还是没通过。获取 Message 字段的时候会直接 throw 一个 Exception。

那么到底该怎么实现呢?

正确的方式#

我们还是按照微软 guideline 进行编写,但是在序列化构造器的上调用 base 的构造器。并且 override 基类的 GetObjectData 方法。

    [Serializable]
    public class MyException : Exception
    {
        public string ErrorCode { get; }

        public MyException()
        {
        }

        public MyException(string message, string errorCode) : base(message)
        {
            ErrorCode = errorCode;
        }

        public MyException(string message, Exception inner): base(message, inner)
        {
        }

        protected MyException(SerializationInfo info, StreamingContext context): base(info, context)
        {
            // Set the ErrorCode value from info dictionary.
            ErrorCode = info.GetString("ErrorCode");
        }

        public override void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            if (!string.IsNullOrEmpty(ErrorCode))
            {
                // Add the ErrorCode to the SerializationInfo dictionary.
                info.AddValue("ErrorCode", ErrorCode);
            }
            base.GetObjectData(info, context);
        }
    }

在序列化构造器里从 SerializationInfo 对象里恢复 ErrorCode 的值。调用 base 的构造可以确保基类的 Message 字段被正确的还原。这里与其说是序列化构造器不如说是反序列化构造器,因为这个构造器会在反序列化恢复成对象的时候被调用。

   protected MyException(SerializationInfo info, StreamingContext context): base(info, context)
        {
            // Set the ErrorCode value from info dictionary.
            ErrorCode = info.GetString("ErrorCode");
        }

这个 GetObjectData 方法是 ISerializable 接口提供的方法,所以基类里肯定有实现。我们的子类需要 override 它。把自己需要序列化的字段添加到 SerializationInfo 对象中,这样在上面反序列化的时候确保可以把字段的值给恢复回来。记住不要忘记调用 base.GetObjectData(info, context), 确保基类的字段数据能正确的被序列化。

    public override void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            if (!string.IsNullOrEmpty(ErrorCode))
            {
                // Add the ErrorCode to the SerializationInfo dictionary.
                info.AddValue("ErrorCode", ErrorCode);
            }
            base.GetObjectData(info, context);
        }

再次运行单元测试,这次顺利的通过了💯,说明 MessageErrorCode 字段在反序列化后成功的被恢复了。

总结#

自定义异常是大家日常编码过程中非常常见的操作。但是看来要写好一个自定义异常类也不是那么简单。总结一下需要注意以下几点:

  1. 添加 [Serializable] Attribute
  2. 遵守微软的 guideline,特别是构造器部分 Designing Custom Exceptions Guideline
  3. 在序列化构造器对字段值进行恢复,不要忘记调用基类的序列化构造器
  4. 重写 GetObjectData 方法,把需要序列化的字段添加到 SerializationInfo 对象上,同样不要忘记调用基类的 GetObjectData
    这个问题虽然在自定义 Exception 上暴露出来,其实可以推广到所有实现 ISerializable 接口的类都需要注意 3,4 两点。

关注我的公众号一起玩转技术#

 

2024-05-20 10:10:08【出处】:https://www.cnblogs.com/kklldog/p/how-to-design-exception.html

=======================================================================================

如何正确实现一个自定义可序列化的 Exception(二)

上一篇《如何正确实现一个自定义 Exception》发布后获得不少 star。有同学表示很担忧,原来自己这么多年一直写错了。其实大家不用过分纠结,如果写的是 .NET CORE 1.0+ 的程序,那么大概率是没有问题的。
有大佬已经在评论区指出这些信息是过时的了。确实在.NET CORE 发布之后,Exception 已经不在推荐实现 ISerializable 接口。让我们细说一下。

BinaryFormatter security vulnerabilities#

上一篇我们谈论了这么多,其实都是在说 ISerializable 的 patten。ISerializable 主要的作用就是给 BinaryFormatter 序列化器提供指示如何进行序列化/反序列化。也就是说这个接口基本上就是给 BinaryFormatter 设计的。BinaryFormatter 主要是给 .NET remoting 技术服务(一种古老的 RPC 技术,听过的都是老司机,不太确定 WCF 的 Binary 序列化是否使用该技术)。
但是很不幸,这个 BinaryFormatter 存在严重的安全风险。

BinaryFormatter 类型会带来风险,不建议将其用于数据处理。 即使应用程序认为自己正在处理的数据是可信的,也应尽快停止使用 BinaryFormatterBinaryFormatter 不安全,无法确保安全。

不光是 BinaryFormatter 有风险,以下这些序列化器同样存在风险,应避免使用:

  • SoapFormatter
  • LosFormatter
  • NetDataContractSerializer
  • ObjectStateFormatter

当前微软主要推荐使用:

  • System.Text.Json
  • XmlSerializer

https://learn.microsoft.com/zh-cn/dotnet/standard/serialization/binaryformatter-security-guide

其实不光是 .NET,其他语言在序列化反序列化上都很容易引入安全漏洞,比如 JAVA 的 jackson 就爆过序列化安全漏洞。

BinaryFormatter Obsolete#

由于 remoting 技术在 .NET CORE 中已经废弃,并且有严重的安全风险,所以微软开始慢慢淘汰 BinaryFormatter 这个接口。
以下是 binaryformatter-obsoletion 的 roadmap:

  • .NET 5 (Nov 2020)
  1. Allow disabling BinaryFormatter via an opt-in feature switch
  2. ASP.NET projects disable BinaryFormatter by default but can re-enable
  3. WASM projects disable BinaryFormatter with no ability to re-enable
  4. All other project types (console, WinForms, etc.) enable BinaryFormatter by default
  5. .NET produces guidance document on migrating away from BinaryFormatter
  6. All outstanding BinaryFormatter-related issues resolved won't fix
  7. Introduce a BinaryFormatter tracing event source
  8. Serialize and Deserialize marked obsolete as warning
  • .NET 6 (Nov 2021)
  1. No new [Serializable] types introduced
  2. No new calls to BinaryFormatter from any first-party dotnet org code base
  3. All first-party dotnet org code bases begin migration away from BinaryFormatter
  • .NET 7 (Nov 2022)
  1. All first-party dotnet org code bases continue migration away from BinaryFormatter
  2. References to BinaryFormatter APIs marked obsolete as warnings in .NET 5 now result
  3. in build errors
  4. A back-compat switch is made available to turn these back to warnings
  • .NET 8 (Nov 2023)
  1. All first-party dotnet org code bases complete migration away from BinaryFormatter
  2. BinaryFormatter disabled by default across all project types
  3. All not-yet-obsolete BinaryFormatter APIs marked obsolete as warning
  4. Additional legacy serialization infrastructure marked obsolete as warning
  5. No new [Serializable] types introduced (all target frameworks)
  • .NET 9 (Nov 2024)
  1. Remainder of legacy serialization infrastructure marked obsolete as warning
  2. BinaryFormatter infrastructure removed from .NET
  3. Back-compat switches also removed

从 .NET5 开始会出现警告,到.NET6 BUILD 的时候直接会是 ERROR,但是可以强制启用。到.NET9 会完全从 .NET 中移除。
那么既然 BinaryFormatter 在目前已经不在推荐使用,自然我们的自定义 Exception 也不用遵循 ISerializable patten 了。以下链接是微软给出的当前自定义 Exception 实现的建议,太长就不复制了。总之已经不在需求实现 protected 的序列化构造器,也不用 override GetObjectData 方法。

https://github.com/dotnet/docs/issues/34893

感谢

  • 饭勺oO
  • czd890

等大佬提供相关链接。

关注我的公众号一起玩转技术#

 

2024-05-20 10:16:45【出处】:https://www.cnblogs.com/kklldog/p/how-to-design-exception-2.html

=======================================================================================

posted on 2024-05-20 10:11  jack_Meng  阅读(12)  评论(0编辑  收藏  举报

导航