Senior
How to create a custom error in Go that can be passed through the error interface?
sobes.tech AI
Answer from AI
In Go, to create a custom error, you need to define a type (usually a struct) that implements the error interface — that is, contains the Error() string method. For 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 doSomething() error {
return &MyError{Code: 404, Message: "Not Found"}
}
func main() {
err := doSomething()
if err != nil {
fmt.Println(err) // Error 404: Not Found
}
}
Thus, a custom error can contain additional fields and logic, and thanks to the implementation of the Error() method, it satisfies the error interface and can be passed and handled as a regular error.