To create a custom error type by embedding the error interface in Go, follow these steps:
error
interface.type CustomError struct {
message string
}
Error()
method for your custom error type. This method should return the error message.func (e CustomError) Error() string {
return e.message
}
func NewCustomError(message string) CustomError {
return CustomError{message}
}
func DoSomething() error {
// ...
if somethingWentWrong {
return NewCustomError("Something went wrong")
}
// ...
}
err := DoSomething()
if customErr, ok := err.(CustomError); ok {
// Handle the custom error
fmt.Println(customErr.message)
} else {
// Handle other types of errors
fmt.Println(err)
}
By embedding the error
interface and implementing the Error()
method, you can create a custom error type with your own error message.