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

비밀번호

댓글 작성자
 




... [61]  62  63  64  65  66  67  68  69  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12400정성태11/5/202014340오류 유형: 679. Visual Studio - "Source Not Found" 창에 "Decompile source code" 링크가 없는 경우
12399정성태11/5/202018120.NET Framework: 961. C# 9.0 - (10) 대상으로 형식화된 조건식(Target-typed conditional expressions)파일 다운로드1
12398정성태11/4/202017324오류 유형: 678. Windows Server 2008 R2 환경에서 Powershell을 psexec로 원격 실행할 때 hang이 발생하는 문제
12397정성태11/4/202017318.NET Framework: 960. C# - 조건 연산자(?:)를 사용하는 경우 달라지는 메서드 선택 사례파일 다운로드1
12396정성태11/3/202014595VS.NET IDE: 152. Visual Studio - "Tools" / "External Tools..."에 등록된 외부 명령어에 대한 단축키 설정 방법
12395정성태11/3/202017199오류 유형: 677. SSMS로 DB 접근 시 The server principal "..." is not able to access the database "..." under the current security context.
12394정성태11/3/202014901오류 유형: 676. cacls - The Recycle Bin on ... is corrupted. Do you want to empty the Recycle Bin for this drive?
12393정성태11/3/202015000오류 유형: 675. Visual Studio - 닷넷 응용 프로그램 디버깅 시 Disassembly 창에서 BP 설정할 때 "Error while processing breakpoint." 오류
12392정성태11/2/202019485.NET Framework: 959. C# 9.0 - (9) 레코드(Records) [4]파일 다운로드1
12390정성태11/1/202018647디버깅 기술: 173. windbg - System.Configuration.ConfigurationErrorsException 예외 분석 방법
12389정성태11/1/202017763.NET Framework: 958. C# 9.0 - (8) 정적 익명 함수 (static anonymous functions)파일 다운로드1
12388정성태10/29/202017327오류 유형: 674. 어느 순간부터 닷넷 응용 프로그램 실행 시 System.Configuration.ConfigurationErrorsException 예외가 발생한다면?
12387정성태10/28/202018053.NET Framework: 957. C# - static 필드의 정보가 GC Heap에 저장될까요? [3]파일 다운로드1
12386정성태10/28/202018548Linux: 34. 사용자 정보를 함께 출력하는 리눅스의 ps 명령어 사용 방법
12385정성태10/28/202016002오류 유형: 673. openssl - req: No value provided for Subject Attribute CN, skipped
12384정성태10/27/202017977오류 유형: 672. AllowPartiallyTrustedCallers 특성이 적용된 어셈블리의 struct 멤버 메서드를 재정의하면 System.Security.VerificationException 예외 발생
12383정성태10/27/202018032.NET Framework: 956. C# 9.0 - (7) 패턴 일치 개선 사항(Pattern matching enhancements) [3]파일 다운로드1
12382정성태10/26/202015952오류 유형: 671. dotnet build - The local source '...' doesn't exist
12381정성태10/26/202017921VC++: 137. C++ stl map의 사용자 정의 타입을 key로 사용하는 방법 [1]파일 다운로드1
12380정성태10/26/202014314오류 유형: 670. Visual Studio - Squash_FailureCommitsReset
12379정성태10/21/202019521.NET Framework: 955. .NET 메서드의 Signature 바이트 코드 분석 [1]파일 다운로드2
12378정성태10/15/202018624.NET Framework: 954. C# - x86/x64 환경에 따라 달라지는 P/Invoke 함수의 export 이름 [1]파일 다운로드1
12377정성태10/15/202018926디버깅 기술: 172. windbg - 파일 열기 시점에 bp를 걸어 파일명 알아내는 방법(Managed/Unmanaged)
12376정성태10/15/202015105오류 유형: 669. windbg - sos의 name2ee 명령어 실행 시 "Failed to request module list." 오류
12375정성태10/15/202016688Windows: 177. 윈도우 탐색기에서 띄우는 cmd.exe 창의 디렉터리 구분 문자가 'Yen(¥)' 기호로 나오는 경우 [1]
12374정성태10/14/202022614.NET Framework: 953. C# 9.0 - (6) 함수 포인터(Function pointers) [1]파일 다운로드2
... [61]  62  63  64  65  66  67  68  69  70  71  72  73  74  75  ...