Golang定義錯誤有兩種方式

  1. errors.New("error message")

  2. 自定義struct,建立方法符合 interface error( Error() string)

    <aside> 💡 可以用指標(Point)。重複使用避免浪費~

    </aside>

    type CustomErr struct {
    	Msg string
    }
    
    func (c CustomErr) Error() string {
    	return fmt.Sprintf("Custom Error with struct. Msg: %s\\n", c.Msg)
    }
    
    func NewCustomErr(msg string) error {
    	return &CustomErr{msg}
    }
    

Error Wrap,產銷履歷,如何追溯錯誤

包裝底層錯誤,增加上下文訊息

errors(原生)

範例

testErr := errors.New("Test Error.")
wrappedErr := fmt.Errorf("bar failed: %w", testErr)
fmt.Printf("wrappedErr: [%v]\\n", wrappedErr)

errFromUnwrap := errors.Unwrap(wrappedErr)
fmt.Printf("wrappedErr is testErr: %v\\n", errors.Is(wrappedErr, testErr))
fmt.Printf("errFromUnwrap is testErr: %v\\n", errors.Is(errFromUnwrap, testErr))

customErr := NewCustomErr("Custom Error.")	
var targetErr *CustomErr
wrappedErrWithCustomErr := fmt.Errorf("Wrapped Custom Error: [%w]", customErr)
isCustomErr := errors.As(wrappedErrWithCustomErr, &targetErr)	
fmt.Printf("\\nisCustomErr: %v\\nCustomErr.Msg: %v\\n", isCustomErr, targetErr.Msg)

// output
// wrappedErr: [bar failed: Test Error.]
// wrappedErr is testErr: true
// errFromUnwrap is testErr: true

// isCustomErr: true
// CustomErr.Msg: Custom Error.

github.com/pkg/errors

相較於原生的erros, github.com/pkg/errors 能夠包含堆疊資訊,更方便於除錯

功能