【发布时间】:2018-04-11 21:56:51
【问题描述】:
我使用基于SO POST 的自定义属性创建了一个客户例外。
但是,当我记录异常时,它没有被序列化。
如果我放置调试器,则不会调用 GetObjectData 方法和 SerializableExceptionWithCustomProperties(SerializationInfo info, StreamingContext context) 构造函数,并且记录器仅记录消息和堆栈跟踪,但不记录我的自定义属性
但是,我在异常中添加了ToString() 方法,当我记录异常时它会被命中,现在我可以构造包含我的自定义属性的字符串并返回它。
那么添加Serializable属性和GetObjectData方法和SerializableExceptionWithCustomProperties(SerializationInfo info, StreamingContext context)构造函数有什么用呢?
我正在使用 Serilog 进行日志记录
[Serializable]
// Important: This attribute is NOT inherited from Exception, and MUST be specified
// otherwise serialization will fail with a SerializationException stating that
// "Type X in Assembly Y is not marked as serializable."
public class SerializableExceptionWithCustomProperties : Exception
{
private readonly string resourceName;
public SerializableExceptionWithCustomProperties()
{
}
public SerializableExceptionWithCustomProperties(string message)
: base(message)
{
}
public SerializableExceptionWithCustomProperties(string message, Exception innerException)
: base(message, innerException)
{
}
public SerializableExceptionWithCustomProperties(string message, string resourceName)
: base(message)
{
this.resourceName = resourceName;
}
public SerializableExceptionWithCustomProperties(string message, string resourceName, Exception innerException)
: base(message, innerException)
{
this.resourceName = resourceName;
}
public string ResourceName
{
get { return this.resourceName; }
}
[SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]
// Constructor should be protected for unsealed classes, private for sealed classes.
// (The Serializer invokes this constructor through reflection, so it can be private)
protected SerializableExceptionWithCustomProperties(SerializationInfo info, StreamingContext context)
: base(info, context)
{
this.resourceName = info.GetString("ResourceName");
}
[SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
// Serialize data for our base classes. base will verify info != null.
base.GetObjectData(info, context);
info.AddValue("ResourceName", this.ResourceName);
}
public override string ToString()
{
return base.ToString() + Environment.NewLine + "ResourceName: " + this.ResourceName;
}
}
【问题讨论】:
标签: c# asp.net exception-handling