0
0
Goprogramming~5 mins

Custom error types in Go - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a custom error type in Go?
A custom error type in Go is a user-defined type that implements the error interface by having an Error() string method. It allows you to create errors with additional context or behavior beyond the basic error message.
Click to reveal answer
beginner
How do you define a custom error type in Go?
You define a custom error type by creating a struct or type and implementing the Error() string method on it. For example:<br>
type MyError struct { Msg string }
func (e MyError) Error() string { return e.Msg }
Click to reveal answer
intermediate
Why use custom error types instead of plain errors?
Custom error types let you add extra information or methods to errors. This helps in identifying error causes, handling errors differently, or adding context like error codes or timestamps.
Click to reveal answer
intermediate
How can you check for a specific custom error type in Go?
You can use a type assertion or errors.As to check if an error is a specific custom error type. For example:<br>
var myErr MyError
if errors.As(err, &myErr) { /* handle MyError */ }
Click to reveal answer
beginner
Show a simple example of a custom error type with additional context.
Example:<br>
type NotFoundError struct { Resource string }
func (e NotFoundError) Error() string {
  return fmt.Sprintf("%s not found", e.Resource)
}
<br>This error tells which resource was not found.
Click to reveal answer
What method must a custom error type implement in Go?
AError() string
BString() string
CMessage() string
DToString() string
Which Go feature helps you check if an error is a specific custom error type?
APanic recovery
BType assertion or errors.As
CReflection only
DInterface embedding
Why might you create a custom error type instead of using errors.New?
ATo make errors print in uppercase
BTo make errors faster
CTo avoid using the error interface
DTo add extra information or behavior to the error
What is the return type of the Error() method in a custom error type?
Astring
Bint
Cbool
Derror
Which of these is a valid custom error type declaration in Go?
Avar MyError = errors.New("error")
Bfunc MyError() error { return "error" }
Ctype MyError struct { Msg string }
Dtype MyError int
Explain how to create and use a custom error type in Go.
Think about how Go's error interface works and how you can add extra info.
You got /4 concepts.
    Why are custom error types useful in Go programming?
    Consider real-life situations where knowing more about an error helps.
    You got /4 concepts.