Custom Errors
Because the error type is just an interface, you can build your own custom types to provide more context and data when something goes wrong.
Example: Custom Struct Error
By defining a struct and implementing the Error() method, you create a custom error type.
type userError struct {
name string
}
func (e userError) Error() string {
return fmt.Sprintf("%v has a problem with their account", e.name)
}
Usage
You can then return this struct whenever an error occurs, and the caller can treat it as a standard Go error.
func checkUser(name string) error {
if name == "" {
return userError{name: "Guest"}
}
return nil
}
Why use custom errors?
Custom errors allow you to store extra metadata (like an error code, a timestamp, or the affected resource ID) that can be accessed later via type assertions or type switches.