Say, there is a class with some methods, that have try catch
blocks. I need to accumulate messages from all inner exceptions of generated exception and use throw new Exception(exceptionMessages)
.
I came up with two possible solutions:
- Create a private method, concatenate inner exception messages, return a
string
and raise an exception in a caller method. (SomeMethod1
below); - Create a private method, concatenate inner exception messages and raise exception inside it. (
SomeMethod2
below);
Code snippet:
class SomeClass
{
private void _raiseException(Exception ex)
{
var exceptionMessages = new StringBuilder();
do
{
exceptionMessages.Append(ex.Message);
ex = ex.InnerException;
}
while (ex != null);
throw new Exception(exceptionMessages.ToString());
}
private string _getInnerExceptions(Exception ex)
{
var exceptionMessages = new StringBuilder();
do
{
exceptionMessages.Append(ex.Message);
ex = ex.InnerException;
}
while (ex != null);
return exceptionMessages.ToString();
}
public void SomeMethod1()
{
try
{
//some code to try
}
catch (Exception e)
{
throw new Exception(this._getInnerExceptions(e));
}
}
public void SomeMethod2()
{
try
{
//some code to try
}
catch (Exception e)
{
this._raiseException(e);
}
}
}
Which one of them would be better, or is there another way of doing it, or maybe this approach is not good at all?
AggregateException
instead? \$\endgroup\$