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

비밀번호

댓글 작성자
 




... 91  92  93  94  95  96  97  98  99  100  101  [102]  103  104  105  ...
NoWriterDateCnt.TitleFile(s)
11382정성태12/4/201721897오류 유형: 436. System.Data.SqlClient.SqlException (0x80131904): Connection Timeout Expired 예외 발생 시 "[Pre-Login] initialization=48; handshake=1944;" 값의 의미
11381정성태11/30/201718320.NET Framework: 702. 한글이 포함된 바이트 배열을 나눈 경우 한글이 깨지지 않도록 다시 조합하는 방법(두 번째 이야기)파일 다운로드1
11380정성태11/30/201718393디버깅 기술: 109. windbg - (x64에서의 인자 값 추적을 이용한) Thread.Abort 시 대상이 되는 스레드를 식별하는 방법
11379정성태11/30/201719116오류 유형: 435. System.Web.HttpException - Session state has created a session id, but cannot save it because the response was already flushed by the application.
11378정성태11/29/201720550.NET Framework: 701. 한글이 포함된 바이트 배열을 나눈 경우 한글이 깨지지 않도록 다시 조합하는 방법 [1]파일 다운로드1
11377정성태11/29/201719843.NET Framework: 700. CommonOpenFileDialog 사용 시 사용자가 선택한 파일 목록을 구하는 방법 [3]파일 다운로드1
11376정성태11/28/201724226VS.NET IDE: 123. Visual Studio 편집기의 \r\n (crlf) 개행을 \n으로 폴더 단위로 설정하는 방법
11375정성태11/28/201718979오류 유형: 434. Visual Studio로 ASP.NET 디버깅 중 System.Web.HttpException - Could not load type 오류
11374정성태11/27/201724085사물인터넷: 14. 라즈베리 파이 - (윈도우의 NT 서비스처럼) 부팅 시 시작하는 프로그램 설정 [1]
11373정성태11/27/201723075오류 유형: 433. Raspberry Pi/Windows 다중 플랫폼 지원 컴파일 관련 오류 기록
11372정성태11/25/201726114사물인터넷: 13. 윈도우즈 사용자를 위한 라즈베리 파이 제로 W 모델을 설정하는 방법 [4]
11371정성태11/25/201719732오류 유형: 432. Hyper-V 가상 스위치 생성 시 Failed to connect Ethernet switch port 0x80070002 오류 발생
11370정성태11/25/201719706오류 유형: 431. Hyper-V의 Virtual Switch 생성 시 "External network" 목록에 특정 네트워크 어댑터 항목이 없는 경우
11369정성태11/25/201721738사물인터넷: 12. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 키보드 및 마우스로 쓰는 방법 (절대 좌표, 상대 좌표, 휠) [1]
11368정성태11/25/201727334.NET Framework: 699. UDP 브로드캐스트 주소 255.255.255.255와 192.168.0.255의 차이점과 이를 고려한 C# UDP 서버/클라이언트 예제 [2]파일 다운로드1
11367정성태11/25/201727455개발 환경 구성: 337. 윈도우 운영체제의 route 명령어 사용법
11366정성태11/25/201719116오류 유형: 430. 이벤트 로그 - Cryptographic Services failed while processing the OnIdentity() call in the System Writer Object.
11365정성태11/25/201721352오류 유형: 429. 이벤트 로그 - User Policy could not be updated successfully
11364정성태11/24/201723283사물인터넷: 11. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스로 쓰는 방법 (절대 좌표) [2]
11363정성태11/23/201723195사물인터넷: 10. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스 + 키보드로 쓰는 방법 (두 번째 이야기)
11362정성태11/22/201719714오류 유형: 428. 윈도우 업데이트 KB4048953 - 0x800705b4 [2]
11361정성태11/22/201722464오류 유형: 427. 이벤트 로그 - Filter Manager failed to attach to volume '\Device\HarddiskVolume??' 0xC03A001C
11360정성태11/22/201722326오류 유형: 426. 이벤트 로그 - The kernel power manager has initiated a shutdown transition.
11359정성태11/16/201721786오류 유형: 425. 윈도우 10 Version 1709 (OS Build 16299.64) 업그레이드 시 발생한 문제 2가지
11358정성태11/15/201726579사물인터넷: 9. Visual Studio 2017에서 Raspberry Pi C++ 응용 프로그램 제작 [1]
11357정성태11/15/201727093개발 환경 구성: 336. 윈도우 10 Bash 쉘에서 C++ 컴파일하는 방법
... 91  92  93  94  95  96  97  98  99  100  101  [102]  103  104  105  ...