Microsoft MVP성태의 닷넷 이야기
VC++: 151. Golang - fmt.Errorf, errors.Is, errors.As 설명 [링크 복사], [링크+제목 복사],
조회: 16263
글쓴 사람
정성태 (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

비밀번호

댓글 작성자
 




... 106  107  108  [109]  110  111  112  113  114  115  116  117  118  119  120  ...
NoWriterDateCnt.TitleFile(s)
11233정성태6/28/201718798오류 유형: 403. SharePoint Server 2013을 Windows Server 2016에 설치할 때 .NET 4.5 설치 오류 발생
11232정성태6/28/201719687Windows: 144. Windows Server 2016에 Windows Identity Extensions을 설치하는 방법
11231정성태6/28/201719540디버깅 기술: 86. windbg의 mscordacwks DLL 로드 문제 - 세 번째 이야기 [1]
11230정성태6/28/201718980제니퍼 .NET: 26. 제니퍼 닷넷 적용 사례 (6) - 잦은 Recycle 문제
11229정성태6/27/201720406오류 유형: 402. Windows Server Backup 관리 콘솔이 없어진 경우
11228정성태6/26/201717507개발 환경 구성: 320. Visual Basic .NET 프로젝트에서 내장 Manifest 자원을 EXE 파일로부터 제거하는 방법파일 다운로드1
11227정성태6/19/201726015개발 환경 구성: 319. windbg에서 python 스크립트 실행하는 방법 - pykd [6]
11226정성태6/19/201717051오류 유형: 401. Microsoft Edge를 실행했는데 입력 반응이 없는 경우
11225정성태6/19/201716331오류 유형: 400. Outlook - The required file ExSec32.dll cannot be found in your path. Install Microsoft Outlook again.
11224정성태6/13/201718827.NET Framework: 661. Json.NET의 DeserializeObject 수행 시 속성 이름을 동적으로 바꾸는 방법파일 다운로드1
11223정성태6/12/201717734개발 환경 구성: 318. WCF Service Application과 WCFTestClient.exe
11222정성태6/10/201721920오류 유형: 399. WCF - A property with the name 'UriTemplateMatchResults' already exists.파일 다운로드1
11221정성태6/10/201719014오류 유형: 398. Fakes - Assembly 'Jennifer5.Fakes' with identity '[...].Fakes, [...]' uses '[...]' which has a higher version than referenced assembly '[...]' with identity '[...]'
11220정성태6/10/201723786.NET Framework: 660. Shallow Copy와 Deep Copy [1]파일 다운로드2
11219정성태6/7/201718871.NET Framework: 659. 닷넷 - TypeForwardedFrom / TypeForwardedTo 특성의 사용법
11218정성태6/1/201721784개발 환경 구성: 317. Hyper-V 내의 VM에서 다시 Hyper-V를 설치: Nested Virtualization
11217정성태6/1/201717944오류 유형: 397. initerrlog: Could not open error log file 'C:\...\MSSQL12.MSSQLSERVER\MSSQL\Log\ERRORLOG'
11216정성태6/1/201719664오류 유형: 396. Activation context generation failed
11215정성태6/1/201721387오류 유형: 395. 관리 콘솔을 실행하면 "This app has been blocked for your protection" 오류 발생 [1]
11214정성태6/1/201718728오류 유형: 394. MSDTC 서비스 시작 시 -1073737712(0xC0001010) 오류와 함께 종료되는 문제 [1]
11213정성태5/26/201724096오류 유형: 393. TFS - The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
11212정성태5/26/201723360오류 유형: 392. Windows Server 2016에 KB4019472 업데이트가 실패하는 경우
11211정성태5/26/201722207오류 유형: 391. BeginInvoke에 전달한 람다 함수에 CS1660 에러가 발생하는 경우
11210정성태5/25/201722519기타: 65. ActiveX 없는 전자 메일에 사용된 "개인정보 보호를 위해 암호화된 보안메일"의 암호화 방법
11209정성태5/25/201770148Windows: 143. Windows 10의 Recovery 파티션을 삭제 및 새로 생성하는 방법 [16]
11208정성태5/25/201728897오류 유형: 390. diskpart의 set id 명령어에서 "The specified type is not in the correct format." 오류 발생
... 106  107  108  [109]  110  111  112  113  114  115  116  117  118  119  120  ...