첨부 실행 코드는 나눔고딕코딩 폰트를 사용합니다.
728x90
반응형
728x170

■ Exception 클래스를 사용해 전체 예외 메시지를 구하는 방법을 보여준다.

 

▶ 예제 코드 (C#)

#region 전체 예외 메시지 구하기 - GetFullExceptionMessage(exception)

/// <summary>
/// 전체 예외 메시지 구하기
/// </summary>
/// <param name="exception">예외</param>
/// <returns>전체 예외 메시지</returns>
public string GetFullExceptionMessage(Exception exception)
{
    IEnumerable<Exception> exceptionEnumerable = GetAllExceptionEnumerable(exception);

    IEnumerable<string> messageEnumerable = exceptionEnumerable.Where(e => !string.IsNullOrWhiteSpace(e.Message))
                                                               .Select(e => e.Message.Trim());

    string totalMessage = string.Join(Environment.NewLine, messageEnumerable);

    return totalMessage;
}

#endregion
#region 모든 예외 열거 가능형 구하기 - GetAllExceptionEnumerable(exception)

/// <summary>
/// 모든 예외 열거 가능형 구하기
/// </summary>
/// <param name="exception">예외</param>
/// <returns>모든 예외 열거 가능형</returns>
private IEnumerable<Exception> GetAllExceptionEnumerable(Exception exception)
{
    yield return exception;

    if(exception is AggregateException aggregateException)
    {
        foreach(Exception innerEx in aggregateException.InnerExceptions.SelectMany(e => GetAllExceptionEnumerable(e)))
        {
            yield return innerEx;
        }
    }
    else if(exception.InnerException != null)
    {
        foreach(Exception innerException in GetAllExceptionEnumerable(exception.InnerException))
        {
            yield return innerException;
        }
    }
}

#endregion
728x90
반응형
그리드형(광고전용)
Posted by icodebroker

댓글을 달아 주세요