Complete the code to define a custom error type named MyError.
type MyError struct {
message string
}
func (e *MyError) Error() string {
return [1]
}The Error() method must return the error message string stored in the struct field message. We access it with e.message.
Complete the code to create a new MyError instance with the message "something went wrong".
func NewMyError() error {
return &MyError{message: [1]
}The message field must be a string literal with quotes. So we use "something went wrong".
Fix the error in the code by completing the blank to implement the error interface.
type MyError struct {
msg string
}
func (e MyError) [1]() string {
return e.msg
}The error interface requires the method Error() that returns a string.
Fill both blanks to create a function that returns a formatted MyError with a dynamic message.
func NewFormattedError(code int, msg string) error {
return &MyError{message: fmt.Sprintf([1], [2], msg)}
}The format string should be "Error %d: %s" and the first argument is the integer code.
Fill both blanks to check if an error is of type *MyError and print its message.
func CheckError(err error) {
var e *MyError
if [1](err, &e) {
fmt.Println(e.[2]())
} else {
fmt.Println("Not a MyError")
}
}Use errors.As to check error type and call Error() method to get the message.