Microsoft MVP성태의 닷넷 이야기
.NET Framework: 104. Win32Exception 클래스 소개 [링크 복사], [링크+제목 복사],
조회: 22566
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 


Win32Exception 클래스 소개


.NET으로 Win32 API를 interop으로 호출을 할 때, 실패를 하면 그 원인을 알아낼 수 없어서 답답하지요. .NET에서는 Exception 클래스에서 친절한 오류 메시지를 알아낼 수 있지만, Win32 API를 호출했을 때는 그렇지 않습니다.

예를 들어 아래와 같은 OpenProcessToken이라는 Win32 API를 이용할 때,

[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool OpenProcessToken(IntPtr processHandle, int acc, out IntPtr pHandleToken);

IntPtr tokenHandle = IntPtr.Zero;
IntPtr processHandle = new IntPtr(-2);

bool result
    = OpenProcessToken(processHandle,
    (int)(0x0020 | 0x00020000 | 0x0008),
    out tokenHandle);

위의 결과는 result == false가 나옵니다. 이런 경우, 왜 실패했는지를 알고 싶다면 Win32 API에서 제공되는 "GetLastError" API를 이용하면 되는데, 이 부분은 .NET BCL의 Marshal 타입에서 정적 메서드로 제공되고 있습니다. 그래서, 다음과 같이 그 원인을 알아낼 수 있습니다.

int errorCode = Marshal.GetLastWin32Error();

위와 같은 상황에서는 errorCode == 6입니다. 그런데, 6이라는 숫자가 어떤 걸 의미할까요? Visual C++에서는 Watch 윈도우의 변수에 ", hr"이라고 치면 오류값이 나옵니다. 아니면, 명령행 창에서 "NET HELPMSG <errorcode>"와 같이 치면 6에 대한 에러 메시지가 "The handle is invalid."라는 것을 알 수 있습니다. (Visual Studio 2008의 경우, C:\Program Files\Microsoft Visual Studio 9.0\Common7\Tools\errlook.exe를 이용하는 것도 가능합니다.)

그렇다면, 코드로는 어떻게 알아낼 수 있을까요?

Visual C++에서는 FormatMessage Win32 API를 이용해서 오류 메시지를 얻어낼 수 있는데요. 인터넷 검색을 해보시면 아시겠지만, 코드가 그다지 깔끔하게 나오지는 않습니다. 기왕이면, .NET에서 제공되는 좀 더 매끄러운 방법을 찾아보는 것이 좋겠지요. ^^

제가 처음에 생각해 냈던 것은 아래와 같은 코드였습니다.

int hr = Marshal.GetHRForLastWin32Error();
Exception ex = Marshal.GetExceptionForHR(hr);
string errorMessage = ex.Message;

실제로 errorMessage == "The handle is invalid. (Exception from HRESULT: 0x80070006 (E_HANDLE))"라고 해서 만족할 만한 수준입니다. 나름 위의 방법도 답이 될 수도 있지만, 원래 Microsoft에서 제공되는 전용 타입이 있는 데 그것이 바로 "Win32Exception"입니다.

그래서, 최종적으로 다음과 같이 코딩을 할 수 있습니다.

int errorCode = Marshal.GetLastWin32Error();
Exception ex = new Win32Exception(errorCode);
string errorMessage = ex.Message; // "The handle is invalid."





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







[최초 등록일: ]
[최종 수정일: 7/10/2021]

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

비밀번호

댓글 작성자
 




... 61  62  [63]  64  65  66  67  68  69  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12398정성태11/4/202019841오류 유형: 678. Windows Server 2008 R2 환경에서 Powershell을 psexec로 원격 실행할 때 hang이 발생하는 문제
12397정성태11/4/202019937.NET Framework: 960. C# - 조건 연산자(?:)를 사용하는 경우 달라지는 메서드 선택 사례파일 다운로드1
12396정성태11/3/202016296VS.NET IDE: 152. Visual Studio - "Tools" / "External Tools..."에 등록된 외부 명령어에 대한 단축키 설정 방법
12395정성태11/3/202019717오류 유형: 677. SSMS로 DB 접근 시 The server principal "..." is not able to access the database "..." under the current security context.
12394정성태11/3/202017226오류 유형: 676. cacls - The Recycle Bin on ... is corrupted. Do you want to empty the Recycle Bin for this drive?
12393정성태11/3/202016096오류 유형: 675. Visual Studio - 닷넷 응용 프로그램 디버깅 시 Disassembly 창에서 BP 설정할 때 "Error while processing breakpoint." 오류
12392정성태11/2/202020701.NET Framework: 959. C# 9.0 - (9) 레코드(Records) [4]파일 다운로드1
12390정성태11/1/202021254디버깅 기술: 173. windbg - System.Configuration.ConfigurationErrorsException 예외 분석 방법
12389정성태11/1/202020280.NET Framework: 958. C# 9.0 - (8) 정적 익명 함수 (static anonymous functions)파일 다운로드1
12388정성태10/29/202018501오류 유형: 674. 어느 순간부터 닷넷 응용 프로그램 실행 시 System.Configuration.ConfigurationErrorsException 예외가 발생한다면?
12387정성태10/28/202019450.NET Framework: 957. C# - static 필드의 정보가 GC Heap에 저장될까요? [3]파일 다운로드1
12386정성태10/28/202020594Linux: 34. 사용자 정보를 함께 출력하는 리눅스의 ps 명령어 사용 방법
12385정성태10/28/202017748오류 유형: 673. openssl - req: No value provided for Subject Attribute CN, skipped
12384정성태10/27/202020569오류 유형: 672. AllowPartiallyTrustedCallers 특성이 적용된 어셈블리의 struct 멤버 메서드를 재정의하면 System.Security.VerificationException 예외 발생
12383정성태10/27/202020734.NET Framework: 956. C# 9.0 - (7) 패턴 일치 개선 사항(Pattern matching enhancements) [3]파일 다운로드1
12382정성태10/26/202018311오류 유형: 671. dotnet build - The local source '...' doesn't exist
12381정성태10/26/202020313VC++: 137. C++ stl map의 사용자 정의 타입을 key로 사용하는 방법 [1]파일 다운로드1
12380정성태10/26/202015610오류 유형: 670. Visual Studio - Squash_FailureCommitsReset
12379정성태10/21/202022073.NET Framework: 955. .NET 메서드의 Signature 바이트 코드 분석 [1]파일 다운로드2
12378정성태10/15/202020582.NET Framework: 954. C# - x86/x64 환경에 따라 달라지는 P/Invoke 함수의 export 이름 [1]파일 다운로드1
12377정성태10/15/202021379디버깅 기술: 172. windbg - 파일 열기 시점에 bp를 걸어 파일명 알아내는 방법(Managed/Unmanaged)
12376정성태10/15/202017014오류 유형: 669. windbg - sos의 name2ee 명령어 실행 시 "Failed to request module list." 오류
12375정성태10/15/202018230Windows: 177. 윈도우 탐색기에서 띄우는 cmd.exe 창의 디렉터리 구분 문자가 'Yen(&#0165;)' 기호로 나오는 경우 [1]
12374정성태10/14/202024305.NET Framework: 953. C# 9.0 - (6) 함수 포인터(Function pointers) [1]파일 다운로드2
12373정성태10/14/202017835.NET Framework: 952. OpCodes.Box와 관련해 IL 형식으로 직접 코딩 시 유의할 점
12372정성태10/13/202020882.NET Framework: 951. C# 9.0 - (5) 로컬 함수에 특성 지정 가능(Attributes on local functions)파일 다운로드1
... 61  62  [63]  64  65  66  67  68  69  70  71  72  73  74  75  ...