Let say we want to extend Error()
function on error
interface. We can simply create a struct derived from string implementing the Error()
method. For example:
type NewUser struct {
Email string
Password string
}
type ErrMissingField string
func (e ErrMissingField) Error() string {
return string(e) + " is required"
}
func (u *NewUser) OK() error {
if len(u.Email) == 0 {
return ErrMissingField("email")
}
if len(u.Password) == 0 {
return ErrMissingField("password")
}
return nil
}
Above code will return either email is required
or password is required
.
But, if I create my own interface, let say ResponseError
, like this:
type ResponseError interface {
ErrorMsg() string
}
type CustomErr string
func (c CustomErr) ErrorMsg() string {
return "[Error] " + string(c)
}
func (u *NewUser) NewOK() ResponseError {
if len(u.Email) == 0 {
return CustomErr("Email required!")
}
if len(u.Password) == 0 {
return CustomErr("Password Required!")
}
return nil
}
It won't print the method implementation I wrote with [Error]
. It just prints the string I passed into the struct Email required!
or Password Required!
.
How to work on this?