Essential Go Error handling  Suggest an edit

Custom error types

In Go error type is a built-in interface with a single method Error() string.

All rules governing interfaces apply to error type.

Among others, any type that implements error interface can be used as value of error type.

// MyError is a custom error type
type MyError struct {
	msg string
}

func (e *MyError) Error() string {
	return e.msg
}

var err error = &MyError{msg: "This is custom error type"}
fmt.Printf("err: %s\n", err)
err: This is custom error type

Why use custom type in addition to built-in ways of creating errors?

Potential use cases are:

  ↑ ↓ to navigate     ↵ to select     Esc to close