Microsoft MVP성태의 닷넷 이야기
.NET Framework: 148. WPF - 데이터 바인딩 시의 예외 처리 방법 [링크 복사], [링크+제목 복사],
조회: 26128
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

(시리즈 글이 4개 있습니다.)
디버깅 기술: 20. 예외 처리를 방해하는 WPF Modal 대화창
; https://www.sysnet.pe.kr/2/0/619

디버깅 기술: 21. 올바른 이벤트 예외 정보 출력
; https://www.sysnet.pe.kr/2/0/620

.NET Framework: 148. WPF - 데이터 바인딩 시의 예외 처리 방법
; https://www.sysnet.pe.kr/2/0/746

.NET Framework: 656. Windows Forms의 오류(Exception) 처리 방법에 대한 차이점 설명
; https://www.sysnet.pe.kr/2/0/11198





WPF 데이터 바인딩 시의 예외 처리 방법


예전에, .NET 응용 프로그램에서 예외 처리를 하는 방법에 관해 정리해놓았지요. ^^

.NET 예외 처리 정리 
; https://www.sysnet.pe.kr/2/0/316

WPF - 전역 예외 처리 
; https://www.sysnet.pe.kr/2/0/614

WPF로 오면서는 유독 First-chance Exception을 구분하는 것이 더 중요해졌습니다. 일례로 아래와 같은 경우들이 모두 "First-chance exception"을 모르면 문제를 해결하는데 헤멜 수가 있습니다.

예외 처리를 방해하는 WPF Modal 대화창
; https://www.sysnet.pe.kr/2/0/619

WPF - XamlParseException 대응 방법
; https://www.sysnet.pe.kr/2/0/622

다시 한번 강조하지만, "First-chance Exception"에 대해서 아직도 모르시는 분들은 부디 이번 기회에 꼭 알고 넘어가시기 바랍니다.

First-Chance Exception
; https://www.sysnet.pe.kr/2/0/510




WPF에서, 예외 처리에 관해 어려움을 겪는 경우가 하나 더 있는데요. 아래의 코드를 보면서 설명해 보겠습니다.

public partial class Window1 : Window, INotifyPropertyChanged
{
    string name2;
    public string Name2
    {
        get { return this.name2; }
        set 
        {
            this.name2 = value;
            OnPropertyChanged("Name2");
            throw new ApplicationException("TEST");
        }
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        this.Name2 = "TEST";
    }
}

보통 위와 같은 상황에서, Visual Studio는 아래와 같이 정상적으로 디버그 지점을 잘 잡아냅니다.

[그림 1: ApplicationException 예외]
not_catch_databind_exception_1.png

하지만, 명시적으로 사용한 this.Name2 = "TEST" 코드를 삭제하고, 대신에 Name2 속성을 데이터바인딩으로 연결하면,

<TextBox Height="30" Margin="16,40,124,0" 
         Text="{Binding Path=Name2}"
/>

이제는 더 이상 Visual Studio IDE에서 예외를 잡아내지 못합니다. 단지 "Output" 창에 다음과 같은 식으로 오류 로그가 출력될 뿐입니다.

A first chance exception of type 'System.ApplicationException' occurred in WpfApplication1.exe
A first chance exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll
System.Windows.Data Error: 8 : Cannot save value from target back to source. BindingExpression:Path=Name2; DataItem='Window1' (Name=''); target element is 'TextBox' (Name='textBox1'); target property is 'Text' (type 'String') TargetInvocationException:'System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.ApplicationException: TEST
   at WpfApplication1.Window1.set_Name2(String value) in D:\Settings\desktop\binding_exception\WpfApplication1\WpfApplication1\Window1.xaml.cs:line 31
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
   at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
   at System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, Object[] index)
   at MS.Internal.Data.PropertyPathWorker.SetValue(Object item, Object value)
   at MS.Internal.Data.ClrBindingWorker.UpdateValue(Object value)
   at System.Windows.Data.BindingExpression.UpdateSource(Object value)'

개인적으로 아쉬운 부분이 바로 위와 같이 데이터 바인딩 구문에서 예외를 먹어버리는 현상입니다. 아쉽긴 해도, WPF의 Validation 정책을 아시는 분들은 이런 식의 동작이 "By design"이라고 수긍이 되는 면이 있습니다.

WPF Sample Series - Handling and Reporting WPF Data Binding Validation Errors and Exceptions
; http://karlshifflett.wordpress.com/2008/04/03/wpf-sample-series-handling-and-reporting-wpf-data-binding-validation-errors-and-exceptions/

그러하니, 유효성 검사에서 자연스럽게 처리될 예외이므로 응용 프로그램 종료로 이어지는 예외 상황을 만들지 않도록 데이터 바인딩 과정에서 try/catch로 예외를 미리 처리하게 된 것입니다. 재미있는 점이 있다면, 마이크로소프트는 DataBinding에 오류가 발생하는 것을 알 수 있도록 그나마 세심하게 배려했다는 정도!

How can I debug WPF bindings?
; http://www.beacosta.com/blog/?p=52

위의 글에 보면, 데이터 바인딩 오류에 대해 "Trace"로 오류 로그를 남기는 방법과 PresentationTraceSources.TraceLevel을 이용한 방법을 소개해 주고 있습니다.

그래도... 이런 거에 만족할 수는 없지요? ^^ 어떻게 해서든지 저는 공용 속성의 set 접근자에서 발생하는 오류를 잡아내야 겠습니다.




단서를 찾을 수 있는 곳은 Validation을 처리하는 코드일 것 같습니다.

WPF Sample Series - Handling and Reporting WPF Data Binding Validation Errors and Exceptions 글에 보면, ExceptionValidationErrorHandler 코드를 볼 수 있는데요.

void ExceptionValidationErrorHandler(object sender, RoutedEventArgs e)
{
    System.Windows.Controls.ValidationErrorEventArgs arg = e as System.Windows.Controls.ValidationErrorEventArgs;

    ;
}

해답은 바로 위의 arg 인자에서 제공되는 Error 속성에 있습니다. 보통 ExceptionValidationErrorHandler가 실행되는 경우는 다음과 같은 2가지 경우입니다.

  • 위에서 설명한 대로 set 접근자에서 오류가 발생한 경우, 또는 타입이 달라서 예외가 발생한 경우
  • IDataErrorInfo를 구현한 개체가 해당 속성의 값이 유효하지 않다고 하는 경우

이 2가지를 구분하려면 arg.Error.RuleInError의 타입으로 검사하면 됩니다.

  • (arg.Error.RuleInError is ExceptionValidationRule) == true: 첫 번째 경우
  • (arg.Error.RuleInError is DataErrorValidationRule) == true: 두 번째 경우

이런 것을 반영해 보면 다음과 같은 식으로 코드를 만들면 될 것 같습니다.

void ExceptionValidationErrorHandler(object sender, RoutedEventArgs e)
{
    System.Windows.Controls.ValidationErrorEventArgs arg = e as System.Windows.Controls.ValidationErrorEventArgs;

    if (arg.Error.Exception != null && arg.Error.RuleInError is ExceptionValidationRule)
    {
        if (arg.Error.Exception is System.FormatException)
        {
            // 대개의 경우 발생할 수 있는 ExceptionValidationRule
        }
        else
        {
            // 그 외의 예외는 의도적이지 않은 예외
            throw arg.Error.Exception.InnerException;
        }
    }
}

이렇게 되면, 타입이 일치하지 않아 발생하는 예외는 그대로 Validation 검사로 진행하도록 하고, 그 이외의 상황에서는 throw를 해서 개발자로 하여금 set 접근자에서 예외가 발생했음을 알 수 있도록 해줍니다.




그나마 예외 상황을 잡아보긴 했지만 아직 해결되지 않은 문제가 있습니다. ExceptionValidationErrorHandler 단계에서는 스택이 이미 풀린 상태이기 때문에 정확히 오류가 발생하는 곳에 코드를 위치시킬 방법이 없습니다. 할 수 없이, 예외가 발생했다는 정도만을 정확하게 인식하고 "throw arg.Error.Exception.InnerException"에서 확인할 수 있는 예외를 디버그 예외 상자에 등록하거나, 아니면 여전히 Output 창의 "First-chance Exception"을 확인해서 디버그 예외 상자에 등록해 두는 식으로 접근해야 합니다.

게다가... 또 한 가지 아쉬운 것은.

Validation 처리 과정으로 넘어오지 않은 예외에 대해서는 여전히 잡을 방법이 없습니다. 예를 들어, 데이터바인딩에는 "Name2"라는 속성명인데, 실제로는 그러한 속성이 없는 경우에는 ExceptionValidationErrorHandler까지 진입하지도 않습니다. 어쩔 수 없이 "How can I debug WPF bindings?"에서 설명한 방식으로 데이터바인딩 예외를 추적하는 방법을 따라야 합니다.

관련 예제 코드는 첨부 파일에 올려놓았습니다.



[이 토픽에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 6/26/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2009-07-03 09시50분
kevin25

1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13511정성태1/4/20242180닷넷: 2193. C# - ASP.NET Web Application + OpenAPI(Swashbuckle) 스펙 제공
13510정성태1/3/20242109닷넷: 2192. C# - 특정 실행 파일이 있는지 확인하는 방법 (Linux)
13509정성태1/3/20242149오류 유형: 887. .NET Core 2 이하의 프로젝트에서 System.Runtime.CompilerServices.Unsafe doesn't support netcoreapp2.0.
13508정성태1/3/20242174오류 유형: 886. ORA-28000: the account is locked
13507정성태1/2/20242836닷넷: 2191. C# - IPGlobalProperties를 이용해 netstat처럼 사용 중인 Socket 목록 구하는 방법파일 다운로드1
13506정성태12/29/20232398닷넷: 2190. C# - 닷넷 코어/5+에서 달라지는 System.Text.Encoding 지원
13505정성태12/27/20232957닷넷: 2189. C# - WebSocket 클라이언트를 닷넷으로 구현하는 예제 (System.Net.WebSockets)파일 다운로드1
13504정성태12/27/20232528닷넷: 2188. C# - ASP.NET Core SignalR로 구현하는 채팅 서비스 예제파일 다운로드1
13503정성태12/27/20232391Linux: 67. WSL 환경 + mlocate(locate) 도구의 /mnt 디렉터리 검색 문제
13502정성태12/26/20232497닷넷: 2187. C# - 다른 프로세스의 환경변수 읽는 예제파일 다운로드1
13501정성태12/25/20232302개발 환경 구성: 700. WSL + uwsgi - IPv6로 바인딩하는 방법
13500정성태12/24/20232370디버깅 기술: 194. Windbg - x64 가상 주소를 물리 주소로 변환
13498정성태12/23/20233056닷넷: 2186. 한국투자증권 KIS Developers OpenAPI의 C# 래퍼 버전 - eFriendOpenAPI NuGet 패키지
13497정성태12/22/20232459오류 유형: 885. Visual Studiio - error : Could not connect to the remote system. Please verify your connection settings, and that your machine is on the network and reachable.
13496정성태12/21/20232442Linux: 66. 리눅스 - 실행 중인 프로세스 내부의 환경변수 설정을 구하는 방법 (gdb)
13495정성태12/20/20232409Linux: 65. clang++로 공유 라이브러리의 -static 옵션 빌드가 가능할까요?
13494정성태12/20/20232555Linux: 64. Linux 응용 프로그램의 (C++) so 의존성 줄이기(ReleaseMinDependency) - 두 번째 이야기
13493정성태12/19/20232657닷넷: 2185. C# - object를 QueryString으로 직렬화하는 방법
13492정성태12/19/20232336개발 환경 구성: 699. WSL에 nopCommerce 예제 구성
13491정성태12/19/20232266Linux: 63. 리눅스 - 다중 그룹 또는 사용자를 리소스에 권한 부여
13490정성태12/19/20232390개발 환경 구성: 698. Golang - GLIBC 의존을 없애는 정적 빌드 방법
13489정성태12/19/20232173개발 환경 구성: 697. GoLand에서 ldflags 지정 방법
13488정성태12/18/20232104오류 유형: 884. HTTP 500.0 - 명령행에서 실행한 ASP.NET Core 응용 프로그램을 실행하는 방법
13487정성태12/16/20232409개발 환경 구성: 696. C# - 리눅스용 AOT 빌드를 docker에서 수행 [1]
13486정성태12/15/20232221개발 환경 구성: 695. Nuget config 파일에 값 설정/삭제 방법
13485정성태12/15/20232101오류 유형: 883. dotnet build/restore - error : Root element is missing
1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...