0
0
Goprogramming~10 mins

Custom error types in Go - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a custom error type named MyError.

Go
type MyError struct {
	message string
}

func (e *MyError) Error() string {
	return [1]
}
Drag options to blanks, or click blank then click option'
Ae.message
Bmessage
Cerror
De
Attempts:
3 left
💡 Hint
Common Mistakes
Returning the variable name 'message' instead of the field value.
Returning the receiver 'e' directly instead of a string.
2fill in blank
medium

Complete the code to create a new MyError instance with the message "something went wrong".

Go
func NewMyError() error {
	return &MyError{message: [1]
}
Drag options to blanks, or click blank then click option'
A"error occurred"
B"something went wrong"
Csomething went wrong
Derror
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting quotes around the string.
Using a variable name instead of a string literal.
3fill in blank
hard

Fix the error in the code by completing the blank to implement the error interface.

Go
type MyError struct {
	msg string
}

func (e MyError) [1]() string {
	return e.msg
}
Drag options to blanks, or click blank then click option'
AMessage
BErrorMsg
CError
DString
Attempts:
3 left
💡 Hint
Common Mistakes
Using a method name other than Error.
Using a pointer receiver instead of value receiver (both work but here value is used).
4fill in blank
hard

Fill both blanks to create a function that returns a formatted MyError with a dynamic message.

Go
func NewFormattedError(code int, msg string) error {
	return &MyError{message: fmt.Sprintf([1], [2], msg)}
}
Drag options to blanks, or click blank then click option'
A"Error %d: %s"
Bcode
Cmsg
D"%s %d"
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping the order of format specifiers and arguments.
Using incorrect format specifiers.
5fill in blank
hard

Fill both blanks to check if an error is of type *MyError and print its message.

Go
func CheckError(err error) {
	var e *MyError
	if [1](err, &e) {
		fmt.Println(e.[2]())
	} else {
		fmt.Println("Not a MyError")
	}
}
Drag options to blanks, or click blank then click option'
Aerrors.As
BError
DError()
Attempts:
3 left
💡 Hint
Common Mistakes
Using type assertion syntax instead of errors.As function.
Calling the wrong method or missing parentheses.