Building an Exception in C#
I have inherited a code-base which uses a compiled logging library. I cannot update the logging library. Thi开发者_高级运维s library has method that logs details for an Exception. The method takes a single Exception as a parameter. I'm now building a mobile application that will tie into this system.
In this mobile application, I have a block of code that handles uncaught exceptions. I need to log those in the server. But now, I can only pass the details across the network in string format. Because of this, I have a service that accepts an error message, stack trace, and miscellaneous as strings. I need to take these strings and convert them into an Exception so I can pass them to my pre-existing library.
How can I take a message and a stackTrace as strings and bundle them into an Exception? The challenge here is Message and StackTrace are read-only.
Thank you!
StackTrace
is virtual so you can define your own Exception
like so:
public class MyException : Exception {
private readonly string stackTrace;
public override string StackTrace { get { return this.stackTrace; } }
public MyException(string message, string stackTrace) : base(message) {
this.stackTrace = stackTrace;
}
}
and then pass instances of MyException
to your logging code. This gives you complete control over the value of Message
and StackTrace
.
Exceptions should be serializable, so you could try serializing the data. Then you can de-serializable it later on and you should have the same exception.
I think the SoapFormatter should allow you to send it over a network, or at least give you a string representation.
精彩评论