Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building an Exception in C#

Tags:

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!

like image 285
user564042 Avatar asked Feb 25 '23 05:02

user564042


1 Answers

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.

like image 53
jason Avatar answered Mar 07 '23 08:03

jason