Go: Create a custom error

First, two out-of-the-box options:

// Simple string-based error:
err1 := errors.New("Houston, we have a problem")

// With formatting:
err2 := fmt.Errorf("%d errors, %d warnings", errCount, warnCount)

Custom errors with data

All you need to do is satisfy the predeclared error interface:

type error interface {
    Error() string
}

Example: Here's a SyntaxError with line and position:

type SyntaxError struct {
        Line int
        Col  int
}

func (e *SyntaxError) Error() string {
        return fmt.Sprintf("%d:%d: Syntax error",
                e.Line, e.Col)
}

You create it as follows:

err := &SyntaxError{
        Line: 17,
        Col:  55,
}

Let's do another one:

Example: Here's an InternalError:

type InternalError struct {
        Path string
}

func (e *InternalError) Error() string {
        return fmt.Sprintf("parse %v: internal error", e.Path)
}

Handling the errors

Suppose RiskyFunction may return a SyntaxError or an InternalError. Here's how you would handle the two cases:

if err := RiskyFunction(); err != nil {
        switch e := err.(type) {
        case *SyntaxError:
                // Do something interesting with e.Line and e.Col.
        case *InternalError:
                // Abort and file an issue.
        default:
                log.Println(e)
        }
}

Comments

Be the first to comment!