Create a custom error type by defining a struct that implements the error interface, then return an instance of it from your function. This allows you to attach specific context or metadata to the error.
type MyError struct {
Code int
Message string
}
func (e MyError) Error() string {
return fmt.Sprintf("error %d: %s", e.Code, e.Message)
}
func DoSomething() error {
return MyError{Code: 404, Message: "not found"}
}