liveBook · Manning

Domain error

As explained in Learn Go with Pocket-Sized Projects

A domain error is an error representing an invalid condition or exceptional outcome specific to an application's problem domain.

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

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Defines a custom error type, sentinel values, wrapping, and errors.As, but stops short of broader error taxonomy.
Examples
Uses malformed decimals and oversized quantities in a money package as concrete domain-error cases.
What it assumes
Assumes familiarity with Go packages and errors while demonstrating the error interface from its basic implementation.
What you can do after
Diagnose/debug with it by classifying parsing failures and adapting caller behavior through errors.As.
How it connects
Connects parsing, the Go error interface, errors.As, package APIs, and numeric range limits.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.