How to create a custom error type by embedding the error interface in Go?

To create a custom error type by embedding the error interface in Go, follow these steps:

  1. Define a new struct type that will represent your custom error type. This struct should embed the error interface.
type CustomError struct { message string }
  1. Implement the Error() method for your custom error type. This method should return the error message.
func (e CustomError) Error() string { return e.message }
  1. Create a constructor function that initializes and returns an instance of your custom error type.
func NewCustomError(message string) CustomError { return CustomError{message} }
  1. Use your custom error type in your code by creating an instance of it using the constructor function.
func DoSomething() error { // ... if somethingWentWrong { return NewCustomError("Something went wrong") } // ... }
  1. To handle the custom error type, you can use a type assertion to check if the returned error is of your custom type.
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.