Junior — Middle
Can you describe the main components that make up the error structure?
sobes.tech AI
Answer from AI
In Go, the error structure typically includes the following main components:
- Error message — a string describing the essence of the error.
- Error type — often implemented through custom types that implement the
errorinterface. This allows distinguishing errors by type. - Wrapped errors — errors can contain other errors to preserve the chain of causes (for example, using
fmt.Errorf("%w", err)). - Stack trace — not built into the standard
error, but can be added using third-party libraries for debugging.
Example of a custom error with additional fields:
package main
import (
"fmt"
)
type MyError struct {
Msg string
Code int
}
func (e *MyError) Error() string {
return fmt.Sprintf("Error %d: %s", e.Code, e.Msg)
}
func main() {
err := &MyError{Msg: "something went wrong", Code: 500}
fmt.Println(err.Error())
}