In Go, an error type represents a failure through the error interface, whose Error() string method supplies a message. A custom type adds structured information or behavior so callers can respond to specific failures. section 4.1.2
Create a custom error when a plain message is insufficient:
- Define fields that describe the failure, such as Message, Line, and Char for a parser error. section 4.1.2
- Implement Error() string by formatting those fields into a readable message. section 4.1.2
- Return the value as an error, allowing callers to inspect additional details or handle error kinds separately. section 4.1.2
- For HTTP APIs, convert unexpected status codes and custom error responses into an error carrying HTTPCode, Code, and Message. section 11.2.2
Listing 4.7 Parse error
type ParseError struct {
Message string #1
Line, Char int #2
}
func (p *ParseError) Error() string { #3
format := "%s o1n Line %d, Char %d" #3
return fmt.Sprintf(format, p.Message, p.Line, p.Char) #3
} #3
Use the ParseError listing to see a concrete struct implement the error interface with location-aware diagnostics. section 4.1.2




