user564042
user564042

Reputation: 185

Building an Exception in C#

I have inherited a code-base which uses a compiled logging library. I cannot update the logging library. This 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!

Upvotes: 4

Views: 149

Answers (2)

Ian
Ian

Reputation: 34519

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.

Upvotes: 1

jason
jason

Reputation: 241711

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.

Upvotes: 7

Related Questions