Custom error types
suggest changeIn Go error
type is a built-in interface with a single method Error() string
.
All rules governing interfaces apply to error
type.
Among others, any type that implements error
interface can be used as value of error
type.
// MyError is a custom error type
type MyError struct {
msg string
}
func (e *MyError) Error() string {
return e.msg
}
var err error = &MyError{msg: "This is custom error type"}
fmt.Printf("err: %s\n", err)
err: This is custom error type
Why use custom type in addition to built-in ways of creating errors?
Potential use cases are:
- wrap existing error and add more information, like a call stack
- add structured information to the error. Code handling the error can check for custom type using type assertion or type switch and access this information
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents