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

비밀번호

댓글 작성자
 




1  2  [3]  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13548정성태2/1/20242302개발 환경 구성: 705. "Docker Desktop for Windows" - ASP.NET Core 응용 프로그램의 소켓 주소 바인딩(IPv4/IPv6 loopback, Any)
13547정성태1/31/20242052개발 환경 구성: 704. Visual Studio - .NET 8 프로젝트부터 dockerfile에 추가된 "USER app" 설정
13546정성태1/30/20241894Windows: 255. (디버거의 영향 등으로) 대상 프로세스가 멈추면 Socket KeepAlive로 연결이 끊길까요?
13545정성태1/30/20241823닷넷: 2212. ASP.NET Core - 우선순위에 따른 HTTP/HTTPS 호스트:포트 바인딩 방법
13544정성태1/30/20241846오류 유형: 894. Microsoft.Data.SqlClient - Could not load file or assembly 'System.Security.Permissions, ...'
13543정성태1/30/20241822Windows: 254. Windows - 기본 사용 중인 5357 포트 비활성화는 방법
13542정성태1/30/20241875오류 유형: 893. Visual Studio - Web Application을 실행하지 못하는 IISExpress - 두 번째 이야기
13541정성태1/29/20241919VS.NET IDE: 188. launchSettings.json의 useSSL 옵션
13540정성태1/29/20242049Linux: 69. 리눅스 - "Docker Desktop for Windows" Container 환경에서 IPv6 Loopback Address 바인딩 오류
13539정성태1/26/20242140개발 환경 구성: 703. Visual Studio - launchSettings.json을 이용한 HTTP/HTTPS 포트 바인딩
13538정성태1/25/20242210닷넷: 2211. C# - NonGC(FOH) 영역에 .NET 개체를 생성파일 다운로드1
13537정성태1/24/20242257닷넷: 2210. C# - Native 메모리에 .NET 개체를 생성파일 다운로드1
13536정성태1/23/20242368닷넷: 2209. .NET 8 - NonGC Heap / FOH (Frozen Object Heap) [1]
13535정성태1/22/20242200닷넷: 2208. C# - GCHandle 구조체의 메모리 분석
13534정성태1/21/20242030닷넷: 2207. C# - SQL Server DB를 bacpac으로 Export/Import파일 다운로드1
13533정성태1/18/20242223닷넷: 2206. C# - TCP KeepAlive의 서버 측 구현파일 다운로드1
13532정성태1/17/20242133닷넷: 2205. C# - SuperSimpleTcp 사용 시 주의할 점파일 다운로드1
13531정성태1/16/20242019닷넷: 2204. C# - TCP KeepAlive에 새로 추가된 Retry 옵션파일 다운로드1
13530정성태1/15/20242007닷넷: 2203. C# - Python과의 AES 암호화 연동파일 다운로드1
13529정성태1/15/20241893닷넷: 2202. C# - PublishAot의 glibc에 대한 정적 링킹하는 방법
13528정성태1/14/20242028Linux: 68. busybox 컨테이너에서 실행 가능한 C++, Go 프로그램 빌드
13527정성태1/14/20241956오류 유형: 892. Visual Studio - Failed to launch debug adapter. Additional information may be available in the output window.
13526정성태1/14/20242043닷넷: 2201. C# - Facebook 연동 / 사용자 탈퇴 처리 방법
13525정성태1/13/20242009오류 유형: 891. Visual Studio - Web Application을 실행하지 못하는 IISExpress
13524정성태1/12/20242062오류 유형: 890. 한국투자증권 KIS Developers OpenAPI - GW라우팅 중 오류가 발생했습니다.
13523정성태1/12/20241885오류 유형: 889. Visual Studio - error : A project with that name is already opened in the solution.
1  2  [3]  4  5  6  7  8  9  10  11  12  13  14  15  ...