Golang / GoLang Interfaces and Object Oriented Interview Questions
How is the built-in error type defined and how do you implement custom errors?
The error type is Go's built-in interface for representing error conditions. It has exactly one method:
type error interface { Error() string }
Any type that has an Error() string method satisfies the error interface. This makes error handling in Go extremely flexible — you can attach arbitrary context to errors by defining custom types.
// Simple sentinel errors var ErrNotFound = errors.New("not found") var ErrPermission = errors.New("permission denied") // Structured custom error type type ValidationError struct { Field string Message string } func (e *ValidationError) Error() string { return fmt.Sprintf("validation failed on %s: %s", e.Field, e.Message) } // Function returning the error interface func validateAge(age int) error { if age < 0 { return &ValidationError{Field: "age", Message: "must be non-negative"} } if age > 150 { return &ValidationError{Field: "age", Message: "unrealistically large"} } return nil // untyped nil â truly nil interface } // Inspect the error type with errors.As err := validateAge(-1) var ve *ValidationError if errors.As(err, &ve) { fmt.Println("Field:", ve.Field, "Message:", ve.Message) } // Wrapped errors (Go 1.13+) â %w preserves the chain func openConfig(path string) error { if err := os.Open(path); err != nil { return fmt.Errorf("openConfig %s: %w", path, err) } return nil } err = openConfig("/missing/config.yaml") if errors.Is(err, os.ErrNotExist) { fmt.Println("config file does not exist") }
More Related questions...