как сериализовать объект исключения как строку XML

2

Мне нужно что-то вроде

try
 {
   //code here
 }
 catch (Exception ex)
  {
    stringXML = Exception.toXML(); 
  }

так что значение stringXML будет

 <exception><message></message><innerException></innerException></exception>

Например...

Как это возможно?

  • 0
    Какова ваша причина сериализации исключения? Вернуться из веб-сервиса? А зачем сериализовать в XML?
Теги:
exception

2 ответа

8
Лучший ответ

Это зависит от того, сколько кода вы хотите написать. Один простой подход - написать свой собственный объект и использовать XmlSerializer:

[XmlRoot("exception"), XmLType("exception")]
public class SerializableException {
    [XmlElement("message")]
    public string Message {get;set;}

    [XmlElement("innerException")]
    public SerializableException InnerException {get;set;}
}

и просто скопируйте в него регулярное исключение. Но так как в любом случае это просто, возможно, XmlWriter достаточно хорош...

public static string GetXmlString(this Exception exception)
{
    if (exception == null) throw new ArgumentNullException("exception");
    StringWriter sw = new StringWriter();
    using (XmlWriter xw = XmlWriter.Create(sw))
    {
        WriteException(xw, "exception", exception);
    }
    return sw.ToString();
}
static void WriteException(XmlWriter writer, string name, Exception exception)
{
    if (exception == null) return;
    writer.WriteStartElement(name);
    writer.WriteElementString("message", exception.Message);
    writer.WriteElementString("source", exception.Source);
    WriteException(writer, "innerException", exception.InnerException);
    writer.WriteEndElement();
}
  • 0
    Что вы подразумеваете под «отображением регулярного исключения в это»?
  • 0
    т.е. создавать новые объекты SerializableException для представления каждого уровня; но подход XmlWriter (обновленный), вероятно, проще
4

Кто-то уже написал запись в блоге об этом

using System;  
using System.Collections;  
using System.Linq;  
using System.Xml.Linq;  

/// <summary>Represent an Exception as XML data.</summary>  
public class ExceptionXElement : XElement  
{  
    /// <summary>Create an instance of ExceptionXElement.</summary>  
    /// <param name="exception">The Exception to serialize.</param>  
    public ExceptionXElement(Exception exception)  
        : this(exception, false)  
    { }  

    /// <summary>Create an instance of ExceptionXElement.</summary>  
    /// <param name="exception">The Exception to serialize.</param>  
    /// <param name="omitStackTrace">  
    /// Whether or not to serialize the Exception.StackTrace member  
    /// if it not null.  
    /// </param>  
    public ExceptionXElement(Exception exception, bool omitStackTrace)  
        : base(new Func<XElement>(() =>  
        {  
            // Validate arguments  

            if (exception == null)  
            {  
                throw new ArgumentNullException("exception");  
            }  

            // The root element is the Exception type  

            XElement root = new XElement  
                (exception.GetType().ToString());  

            if (exception.Message != null)  
            {  
                root.Add(new XElement("Message", exception.Message));  
            }  

            // StackTrace can be null, e.g.:  
            // new ExceptionAsXml(new Exception())  

            if (!omitStackTrace && exception.StackTrace != null)  
            {  
                root.Add  
                (  
                    new XElement("StackTrace",  
                        from frame in exception.StackTrace.Split('\n')  
                        let prettierFrame = frame.Substring(6).Trim()  
                        select new XElement("Frame", prettierFrame))  
                );  
            }  

            // Data is never null; it empty if there is no data  

            if (exception.Data.Count > 0)  
            {  
                root.Add  
                (  
                    new XElement("Data",  
                        from entry in  
                            exception.Data.Cast<DictionaryEntry>()  
                        let key = entry.Key.ToString()  
                        let value = (entry.Value == null) ?  
                            "null" : entry.Value.ToString()  
                        select new XElement(key, value))  
                );  
            }  

            // Add the InnerException if it exists  

            if (exception.InnerException != null)  
            {  
                root.Add  
                (  
                    new ExceptionXElement  
                        (exception.InnerException, omitStackTrace)  
                );  
            }  

            return root;  
        })())  
    { }  
}

Ещё вопросы

Сообщество Overcoder
Наверх
Меню