Refactoring
This commit is contained in:
41
AMWD.Common/Extensions/ExceptionExtensions.cs
Normal file
41
AMWD.Common/Extensions/ExceptionExtensions.cs
Normal file
@@ -0,0 +1,41 @@
|
||||
using System.Linq;
|
||||
|
||||
namespace System
|
||||
{
|
||||
/// <summary>
|
||||
/// Provides extension methods for exceptions.
|
||||
/// </summary>
|
||||
public static class ExceptionExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns the message of the inner exception if exists otherwise the message of the exception itself.
|
||||
/// </summary>
|
||||
/// <param name="exception">The exception.</param>
|
||||
/// <returns>The message of the inner exception or the exception itself.</returns>
|
||||
public static string GetMessage(this Exception exception)
|
||||
=> exception.InnerException?.Message ?? exception.Message;
|
||||
|
||||
/// <summary>
|
||||
/// Returns the message of the exception and its inner exceptions.
|
||||
/// </summary>
|
||||
/// <param name="exception">The exception.</param>
|
||||
/// <returns>The message of the <paramref name="exception"/> and all its inner exceptions.</returns>
|
||||
public static string GetRecursiveMessage(this Exception exception)
|
||||
{
|
||||
if (exception is AggregateException aggregateEx)
|
||||
{
|
||||
return aggregateEx.InnerExceptions
|
||||
.Take(3)
|
||||
.Select(ex => ex.GetRecursiveMessage())
|
||||
.Aggregate((a, b) => a + " " + b);
|
||||
}
|
||||
if (exception.InnerException != null)
|
||||
{
|
||||
string message = exception.Message;
|
||||
message = message.ReplaceEnd(" See the inner exception for details.", "");
|
||||
return message + " " + exception.InnerException.GetRecursiveMessage();
|
||||
}
|
||||
return exception.Message;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user