A domain error represents an invalid condition or exceptional outcome specific to an application's problem domain. In Go, expose it through a package-specific type so callers can recognize it and adapt their behavior. section 6.2.4
A money package can expose errors that consumers understand:
- ErrInvalidDecimal indicates malformed input that cannot be parsed as a decimal. section 6.2.4
- ErrTooLarge indicates a quantity beyond the supported limit, preventing unsafe numeric operations. section 6.2.4
- Callers can use errors.As to compare an error's concrete value with the package's domain error type. section 6.2.4
A package-specific error type
type Error string func (e Error) Error() string { return string(e) } const ErrInvalidDecimal = Error("unable to convert the decimal") ParseDecimal wraps the underlying parsing failure with ErrInvalidDecimal, allowing callers to identify the domain condition while retaining diagnostic detail. section 6.2.4
Listing 6.7 errors.go: Custom error type for the money package
package money
// Error defines an error.
type Error string
// Error implements the error interface.
func (e Error) Error() string {
return string(e)
}
Inspect the minimal custom error type that implements Go's error interface. section 6.2.4
