Microsoft MVP성태의 닷넷 이야기
VC++: 151. Golang - fmt.Errorf, errors.Is, errors.As 설명 [링크 복사], [링크+제목 복사],
조회: 15300
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

Golang - fmt.Errorf, errors.Is, errors.As 설명

예를 들어, 간단하게 (존재하지 않는) 파일을 열어 에러가 발생했을 때를 보겠습니다.

package main

import (
    "fmt"
    "os"
)

func main() {
    defer func() {
        if err := recover(); err != nil {
            fmt.Printf("main: %v", err)
        }
    }()

    doWork()
}

func doWork() {

    _, err := os.Open("test.dat")
    if err != nil {
        panic(err)
    }
}

우리가 여기서 하고 싶은 것은, panic 시 "사용자 오류 메시지"를 덧붙이고 싶은 것입니다. 이에 대해서는 다양한 방법이 있을 텐데요, 우선 struct로 감싸는 방식을 쓸 수 있습니다.

package main

import (
    "fmt"
    "os"
    "reflect"
)

func main() {
    defer func() {
        if err := recover(); err != nil {
            if e, ok := err.(struct { msg string; err error }); ok {
                fmt.Printf("struct error: %s, %v", e.msg, e.err)
            }
        }

        /* reflection을 써도 되고!
        if err := recover(); err != nil {
            r := reflect.ValueOf(err)
            innerError := reflect.Indirect(r).FieldByName("err")
            innerMsg := reflect.Indirect(r).FieldByName("msg")
            fmt.Printf("main: %v\n", innerError)
            fmt.Printf("main: %v\n", innerMsg)
        }
        */
    }()

    doWork()
}

func doWork() {

    file, err := os.Open("test.dat")
    if err != nil {
        panic(struct { msg string; err error }{"doWork failed", err})
    }

    defer file.Close()
}

위의 코드에서 구조체만 명시적으로 정의하는 것으로 다음과 같이 바꿀 수 있습니다.

type WrapError struct { Message string; Err error }

/* 기왕 만든 구조체에 다음의 메서드만 추가하면 error 인터페이스를 따르게 됩니다.
func (e *WrapError) Error() string { return "WrapError.Error(): " + e.Message + ": " + e.Err.Error() }
*/

func main() {
    defer func() {
        err := recover()

        if err == nil {
	        return
        }

        if e, ok := err.(WrapError); ok {}
            fmt.Printf("wrapError message == %v\n", e)
			fmt.Printf("main: %v\n", e.Err)
			fmt.Printf("main: %v\n", e.Message)
        }
    }()

    doWork()
}

func doWork() {

    file, err := os.Open("test.dat")
    if err != nil {
        panic(WrapError{"doWork failed", err})
    }

    defer file.Close()
}
/* 출력 결과
wrapError message == {0xc000072480 doWork failed}
main: open test.dat: The system cannot find the file specified.
main: doWork failed
*/

그런데, 사실 위와 같은 경우에 진짜 오류는 Err 필드에 담겨 있으므로 그것의 종류에 따라 처리하고 싶을 때가 있습니다. 당연히, 다음과 같은 식으로 직접 recover가 반환한 err에 대해 타입 조회를 할 수 없습니다.

// ok == False
if e, ok := err.(fs.PathError); ok {
    fmt.Printf("PathError: main: %v\n", e.Err)
}

대신 내부 속성을 접근해 재차 묻는 형태로 코딩해야 합니다.

if e, ok := err.(WrapError); ok  {
    if inner, ok := e.Err.(*fs.PathError); ok {
        fmt.Printf("%v\n", inner)
    }
}

일단 해결을 한 듯 보이지만, 사실 우리가 원하는 종류의 오류 타입이 다시 그 하위에, 또다시 그 하위에 감싸인 것인지 알 수 없으므로 완벽한 해결책은 아닙니다. 바로 이런 문제 때문에 이후 설명할 errors.Is, errors.As가 나옵니다. ^^




위의 경우 우리가 WrapError를 구현했는데요, Go 언어 측에는 이미 이 용도로 (private 접근이지만) fmt.wrapError라는 타입이 있습니다.

/*
// 명시적으로는 없고 필요할 때만 인라인 정의
interface { Unwrap() error }

// builtin.go에 정의
type error interface {
	Error() string
}
*/

type wrapError struct {
    msg string
    err error
}

func (e *wrapError) Error() string {
    return e.msg
}

func (e *wrapError) Unwrap() error {
    return e.err
}

보는 바와 같이 내부 필드 2개가 모두 private 접근이고, 대신 error 인터페이스의 함수인 Error()를 통해 msg를 반환하고, 필요할 때마다 Unwrap을 포함한 인라인 인터페이스를 조회해 내부 err 필드를 접근할 수 있습니다.

그리고, 저렇게 기존 에러와 새로운 에러 메시지를 합쳐 fmt.wrapError를 반환해 주는 함수가 "%w" 인자를 이용한 fmt.Errorf입니다.

file, err := os.Open("test.dat")
if err != nil {
    wrapped := fmt.Errorf("doWork failed: %w", err)
    fmt.Printf("wrapped: %v, %T\n", wrapped, wrapped)
    /* 출력 결과
wrapped: doWork failed: open test.dat: The system cannot find the file specified., *fmt.wrapError
    */
}

fmt.Errorf는 (msg == "doWork failed: %w", err), (err == err)로 설정된 fmt.wrapError 인스턴스를 반환하고, 이런 경우 다음과 같이 errors.Is 함수를 사용해 (값에 대한) 비교를 하면,

if errors.Is(wrapped, err) { // true 평가
    fmt.Printf("errors.Is Error %v\n", wrapped)
}

2개의 error 개체가 같다고 판정을 합니다. 그런데 이상하지 않나요? Errorf가 반환한 fmt.wrapError가 왜 fs.PathError와 같은 걸까요? 왜냐하면, errors.Is는 내부적으로 Unwrap을 호출하는데,

// wrap.go에 errors.Is, Unwrap 정의

// errors.Is가 호출하는 Unwrap 함수
func Unwrap(err error) error {
    u, ok := err.(interface { Unwrap() error })
    if !ok {
        return nil
    }
    return u.Unwrap()
}

func Is(err, target error) bool {
    if target == nil {
        return err == target
    }

    isComparable := reflectlite.TypeOf(target).Comparable()
    for {}
        if isComparable && err == target {
            return true
        }
        if x, ok := err.(interface{ Is(error) bool }); ok && x.Is(target) {
            return true
        }
        // TODO: consider supporting target.Is(err). This would allow
        // user-definable predicates, but also may allow for coping with sloppy
        // APIs, thereby making it easier to get away with them.
        if err = Unwrap(err); err == nil {
            return false
        }
    }
}

보는 바와 같이 해당 개체가 interface { Unwrap() error }을 구현하고 있는지 확인하므로 결국 fmt.wrapError의 Unwrap 함수가 불려 내부에 감싸진 에러와 비교를 하기 때문입니다.

위와 같은 동작 방식으로 인해 실수할 여지가 하나 있습니다. 개발자가 임의로 만든 error 타입이 있다면 반드시 Unwrap도 구현해줘야만 errors.Is(및 errors.As) 코드가 정상적으로 동작할 수 있다는 점입니다. (물론 에러 간의 연결 고리를 유지하지 않을 error 타입이라면 저런 고려 자체가 의미가 없습니다.)




errors.Is의 Unwrap 동작은 errors.As에서도 동일하게 발생합니다. 따라서, fmt.Errorf를 이용해 panic 처리한 오류라면 recover로 반환한 에러 개체에 대해 다음과 같이 직접 오류 타입으로의 형변환 가능성을 테스트할 수 있습니다.

func main() {
    defer func() {
        if e := recover(); e != nil {
            var pathError *fs.PathError

            // fs.PathError인 경우에만 처리하도록 분기 (타입에 해당한다면 그 형식으로 변환한 인스턴스를 반환)
            if errors.As(e.(error), &pathError) {
                fmt.Printf("errors.As: %v\n", e)
            }
        }
    }()

    doWork()
}

func doWork() {

    file, err := os.Open("test.dat")
    if err != nil {
        panic(fmt.Errorf("doWork failed: %w", err))
    }

    defer file.Close()
}

하지만, 이게 범용적으로 쓸 수 있는 defer 루틴이 아닙니다. 일례로 다음과 같이 코드를 바꾸면,

func doWork() {
    // ...[생략]...
    panic("Test")
}

errors.As에서 fatalpanic으로 빠지는 것을 볼 수 있습니다. 왜냐하면 (recover는 "interface {}" 타입을 반환하고) errors.As의 첫 번째 인자는 반드시 error 타입이어야 하기 때문입니다. 그래서 defer의 코드가 이렇게 바뀌어야 합니다.

defer func() {
    if e := recover(); e != nil {
        if err, ok := e.(error); ok {
            var pathError *fs.PathError
            if errors.As(err, &pathError) {
                fmt.Printf("errors.As: %v\n", e)
            }
        }
    }
}()

이와 관련해 실수할 수 있는 또 다른 사용법이 바로 log.go의 log.Panic을 다음과 같은 식으로 사용하는 경우입니다.

file, err := os.Open("test.dat")
if err != nil {
    log.Panic(fmt.Errorf("failed to send data to data server: %w", err))
    // 위의 코드는 사실상 아래의 코드와 동일합니다.
    // log.Panicf("failed to send data to data server: ... %v", err.Error())
}

왜냐하면 log.Panic의 내부 구현이,

func Panic(v ...interface{}) {
    s := fmt.Sprint(v...)
    std.Output(2, s)
    panic(s)
}

결국 문자열 반환이기 때문에 fmt.Errorf를 사용하는 의미가 없습니다. 즉, log.Panic을 사용하면 위에서 만든 errors.As + fs.PathError 테스트 코드가 동작하지 않습니다. (log.Panic + fmt.Errorf의 원래 의도대로라면 panic + fmt.Errorf로 해야 맞습니다.) 왠지... Go 언어의 예외 처리 방식이 산만한다고 느껴지지 않나요? ^^;




마지막으로, 그나마 마음에 드는 콜스택을 알아보겠습니다. 이것은 그냥 debug.Stack()을 사용하면 끝입니다.

defer func() {
    if e := recover(); e != nil {
        fmt.Printf("error: %v, %s\n", e, debug.Stack())
    }
}()

재미있는 건, panic을 호출 스택에서 중첩시킨 경우입니다.

func do2Work() {
    defer func() {
        if e := recover(); e != nil {
            panic("failed")
        }
    }()

    doWork()
}

func doWork() {

    file, err := os.Open("test.dat")
    if err != nil {
        wrapped := fmt.Errorf("doWork failed: %w", err)
        panic(wrapped)
    }

    defer file.Close()
}

별다르게 panic 정보를 연결하지도 않았는데, 마지막의 debug.Stack()에서는 중간에 panic("failed")을 호출한 것에 상관없이 전체 호출 스택 정보를 보여줍니다.

runtime/debug.Stack()
    C:/Go/src/runtime/debug/stack.go:24 +0x65
main.main.func1()
    C:/gowork/work/panicTest/main.go:19 +0x39
panic({0xbc7c40, 0xbf9aa0})
    C:/Go/src/runtime/panic.go:1038 +0x215
main.do2Work.func1()
    C:/gowork/work/panicTest/main.go:118 +0x45
panic({0xbcb0c0, 0xc0000a4400})
    C:/Go/src/runtime/panic.go:1038 +0x215
main.doWork()
    C:/gowork/work/panicTest/main.go:140 +0xc5
main.do2Work()
    C:/gowork/work/panicTest/main.go:122 +0x3b
main.main()
    C:/gowork/work/panicTest/main.go:90 +0x3b




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







[최초 등록일: ]
[최종 수정일: 9/11/2021]

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

비밀번호

댓글 작성자
 




... 121  122  123  124  125  126  127  128  129  130  [131]  132  133  134  135  ...
NoWriterDateCnt.TitleFile(s)
1780정성태10/15/201424176오류 유형: 249. The application-specific permission settings do not grant Local Activation permission for the COM Server application with CLSID
1779정성태10/15/201419706오류 유형: 248. Active Directory에서 OU가 지워지지 않는 경우
1778정성태10/10/201418156오류 유형: 247. The Netlogon service could not create server share C:\Windows\SYSVOL\sysvol\[도메인명]\SCRIPTS.
1777정성태10/10/201421247오류 유형: 246. The processing of Group Policy failed. Windows attempted to read the file \\[도메인]\sysvol\[도메인]\Policies\{...GUID...}\gpt.ini
1776정성태10/10/201418296오류 유형: 245. 이벤트 로그 - Name resolution for the name _ldap._tcp.dc._msdcs.[도메인명]. timed out after none of the configured DNS servers responded.
1775정성태10/9/201419425오류 유형: 244. Visual Studio 디버깅 (2) - Unable to break execution. This process is not currently executing the type of code that you selected to debug.
1774정성태10/9/201426621개발 환경 구성: 246. IIS 작업자 프로세스의 20분 자동 재생(Recycle)을 끄는 방법
1773정성태10/8/201429777.NET Framework: 471. 웹 브라우저로 다운로드가 되는 파일을 왜 C# 코드로 하면 안되는 걸까요? [1]
1772정성태10/3/201418569.NET Framework: 470. C# 3.0의 기본 인자(default parameter)가 .NET 1.1/2.0에서도 실행될까? [3]
1771정성태10/2/201428077개발 환경 구성: 245. 실행된 프로세스(EXE)의 명령행 인자를 확인하고 싶다면 - Sysmon [4]
1770정성태10/2/201421687개발 환경 구성: 244. 매크로 정의를 이용해 파일 하나로 C++과 C#에서 공유하는 방법 [1]파일 다운로드1
1769정성태10/1/201424108개발 환경 구성: 243. Scala 개발 환경 구성(JVM, 닷넷) [1]
1768정성태10/1/201419531개발 환경 구성: 242. 배치 파일에서 Thread.Sleep 효과를 주는 방법 [5]
1767정성태10/1/201424630VS.NET IDE: 94. Visual Studio 2012/2013에서의 매크로 구현 - Visual Commander [2]
1766정성태10/1/201422481개발 환경 구성: 241. 책 "프로그래밍 클로저: Lisp"을 읽고 나서. [1]
1765정성태9/30/201426052.NET Framework: 469. Unity3d에서 transform을 변수에 할당해 사용하는 특별한 이유가 있을까요?
1764정성태9/30/201422287오류 유형: 243. 파일 삭제가 안 되는 경우 - The action can't be comleted because the file is open in System
1763정성태9/30/201423853.NET Framework: 468. PDB 파일을 연동해 소스 코드 라인 정보를 알아내는 방법파일 다운로드1
1762정성태9/30/201424549.NET Framework: 467. 닷넷에서 EIP/RIP 레지스터 값을 구하는 방법 [1]파일 다운로드1
1761정성태9/29/201421570.NET Framework: 466. 윈도우 운영체제의 보안 그룹 이름 및 설명 문자열을 바꾸는 방법파일 다운로드1
1760정성태9/28/201419835.NET Framework: 465. ICorProfilerInfo::GetILToNativeMapping 메서드가 0x80131358을 반환하는 경우
1759정성태9/27/201430977개발 환경 구성: 240. Visual C++ / x64 환경에서 inline-assembly를 매크로 어셈블리로 대체하는 방법파일 다운로드1
1758정성태9/23/201437882개발 환경 구성: 239. 원격 데스크톱 접속(RDP)을 기존의 콘솔 모드처럼 사용하는 방법 [1]
1757정성태9/23/201418408오류 유형: 242. Lync로 모임 참여 시 소리만 들리지 않는 경우 - 두 번째 이야기
1756정성태9/23/201427409기타: 48. NVidia 제품의 과다한 디스크 사용 [2]
1755정성태9/22/201434202오류 유형: 241. Unity Web Player를 설치해도 여전히 설치하라는 화면이 나오는 경우 [4]
... 121  122  123  124  125  126  127  128  129  130  [131]  132  133  134  135  ...