0

I have a chain of methods. In every method I have try/catch block like the following sample:

public void DoCommand() {
    try {
        GetData();
    }
    catch(Exception ex) {
        // I want to show the following and all inner exceptions
        // in correct order here (User-friendly stack trace)
    }
}

public void GetData() {
    try {
        GetLowLevelData();
    }
    catch(Exception ex) {
        throw new Exception("Get Data exception", ex);
    }
}

public void GetLowLevelData() {
    try {
        // do something
    }
    catch(Exception ex) {
        throw new Exception("Get Low Level Data exception", ex);
    }
}

What's good approach to collect inner exceptions to log it in DoCommand method?

pepeevich
  • 183
  • 1
  • 4
  • 20
  • You don't need to do anything. A stack trace already contains all inner exceptions data. If you need to convert it to string you can call `ex.ToString()` – Fabjan Apr 23 '18 at 10:48
  • Maybe `ex.ToString()` is what you are looking for... – JiBéDoublevé Apr 23 '18 at 10:50
  • you can print exception message using `ex.Message` property, As @Fabjan said everything will be taken care by stack trace – Prasad Telkikar Apr 23 '18 at 10:51
  • I want to show messages stack trace, without any additional information that I get in ex. Only messages of inner exceptions in correct order. – pepeevich Apr 23 '18 at 10:52
  • This is a little convoluted, why does the user care about exceptions caught 3 layers down. the fact is if you cant handle it there, you shouldn't be catching it. In my opinion you should be aware of what possible exceptions happen at what layer in your code. More so catching all exceptions with `catch(Exception ex)` and wrapping them in `Exception` again seems to be your problem. – TheGeneral Apr 23 '18 at 10:53
  • TheGeneral, I read the exception emergence is a good approach. I delegate exception handling to one class (look S in SOLID principles). It is sample, and these methods are placed in different classes. I just simplify my sample. – pepeevich Apr 23 '18 at 10:58

0 Answers0