Microsoft MVP성태의 닷넷 이야기
.NET Framework: 148. WPF - 데이터 바인딩 시의 예외 처리 방법 [링크 복사], [링크+제목 복사],
조회: 26125
글쓴 사람
정성태 (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)
13536정성태1/23/20242594닷넷: 2209. .NET 8 - NonGC Heap / FOH (Frozen Object Heap) [1]
13535정성태1/22/20242453닷넷: 2208. C# - GCHandle 구조체의 메모리 분석
13534정성태1/21/20242255닷넷: 2207. C# - SQL Server DB를 bacpac으로 Export/Import파일 다운로드1
13533정성태1/18/20242470닷넷: 2206. C# - TCP KeepAlive의 서버 측 구현파일 다운로드1
13532정성태1/17/20242360닷넷: 2205. C# - SuperSimpleTcp 사용 시 주의할 점파일 다운로드1
13531정성태1/16/20242253닷넷: 2204. C# - TCP KeepAlive에 새로 추가된 Retry 옵션파일 다운로드1
13530정성태1/15/20242204닷넷: 2203. C# - Python과의 AES 암호화 연동파일 다운로드1
13529정성태1/15/20242066닷넷: 2202. C# - PublishAot의 glibc에 대한 정적 링킹하는 방법
13528정성태1/14/20242188Linux: 68. busybox 컨테이너에서 실행 가능한 C++, Go 프로그램 빌드
13527정성태1/14/20242132오류 유형: 892. Visual Studio - Failed to launch debug adapter. Additional information may be available in the output window.
13526정성태1/14/20242220닷넷: 2201. C# - Facebook 연동 / 사용자 탈퇴 처리 방법
13525정성태1/13/20242169오류 유형: 891. Visual Studio - Web Application을 실행하지 못하는 IISExpress
13524정성태1/12/20242234오류 유형: 890. 한국투자증권 KIS Developers OpenAPI - GW라우팅 중 오류가 발생했습니다.
13523정성태1/12/20242038오류 유형: 889. Visual Studio - error : A project with that name is already opened in the solution.
13522정성태1/11/20242207닷넷: 2200. C# - HttpClient.PostAsJsonAsync 호출 시 "Transfer-Encoding: chunked" 대신 "Content-Length" 헤더 처리
13521정성태1/11/20242270닷넷: 2199. C# - 한국투자증권 KIS Developers OpenAPI의 WebSocket Ping, Pong 처리
13520정성태1/10/20242016오류 유형: 888. C# - Unable to resolve service for type 'Microsoft.Extensions.ObjectPool.ObjectPool`....'
13519정성태1/10/20242104닷넷: 2198. C# - Reflection을 이용한 ClientWebSocket의 Ping 호출파일 다운로드1
13518정성태1/9/20242369닷넷: 2197. C# - ClientWebSocket의 Ping, Pong 처리
13517정성태1/8/20242210스크립트: 63. Python - 공개 패키지를 이용한 위성 이미지 생성 (pystac_client, odc.stac)
13516정성태1/7/20242319닷넷: 2196. IIS - AppPool의 "Disable Overlapped Recycle" 옵션의 부작용
13515정성태1/6/20242597닷넷: 2195. async 메서드 내에서 C# 7의 discard 구문 활용 사례 [1]
13514정성태1/5/20242275개발 환경 구성: 702. IIS - AppPool의 "Disable Overlapped Recycle" 옵션
13513정성태1/5/20242202닷넷: 2194. C# - WebActivatorEx / System.Web의 PreApplicationStartMethod 특성
13512정성태1/4/20242159개발 환경 구성: 701. IIS - w3wp.exe 프로세스의 ASP.NET 런타임을 항상 Warmup 모드로 유지하는 preload Enabled 설정
13511정성태1/4/20242177닷넷: 2193. C# - ASP.NET Web Application + OpenAPI(Swashbuckle) 스펙 제공
1  2  3  [4]  5  6  7  8  9  10  11  12  13  14  15  ...