How to create custom error types

Create a custom error type in Go by defining a struct with an Error() method and returning it from your functions.

Create a custom error type by defining a struct that implements the error interface, then return an instance of it from your function. This allows you to attach specific context or metadata to the error.

type MyError struct {
	Code    int
	Message string
}

func (e MyError) Error() string {
	return fmt.Sprintf("error %d: %s", e.Code, e.Message)
}

func DoSomething() error {
	return MyError{Code: 404, Message: "not found"}
}