To create custom error types that implement the error
interface in Go, you need to define a new type that satisfies the error
interface. Here's an example:
package main
import (
"fmt"
)
type MyError struct {
Code int
Message string
}
func (e *MyError) Error() string {
return fmt.Sprintf("Error: %d - %s", e.Code, e.Message)
}
func main() {
err := &MyError{Code: 500, Message: "Internal Server Error"}
fmt.Println(err.Error())
}
In the above code:
MyError
with two fields Code
and Message
.Error()
method for the MyError
type. This method satisfies the error
interface by returning a string representation of the error.main()
function, we create an instance of MyError
and print the error by calling err.Error()
, which implicitly calls the Error()
method we defined.The output will be: "Error: 500 - Internal Server Error".
By creating custom error types like this, you can provide more detailed and meaningful error messages in your Go programs.