How to Create Custom Error Type in Go: Simple Guide
In Go, create a custom error type by defining a struct and implementing the
Error() method that returns a string. This lets you return detailed error information while still satisfying the error interface.Syntax
To create a custom error type, define a struct to hold error details and implement the Error() method that returns a string message. This method makes your struct satisfy Go's error interface.
- Struct: Holds error information.
- Error() method: Returns the error message as a string.
go
type MyError struct { Msg string } func (e MyError) Error() string { return e.Msg }
Example
This example shows a custom error type MyError with a message. The doSomething function returns this error, and the main function prints it.
go
package main import ( "fmt" ) type MyError struct { Msg string } func (e MyError) Error() string { return e.Msg } func doSomething(fail bool) error { if fail { return MyError{Msg: "something went wrong"} } return nil } func main() { err := doSomething(true) if err != nil { fmt.Println("Error:", err) } else { fmt.Println("Success") } }
Output
Error: something went wrong
Common Pitfalls
Common mistakes include:
- Not implementing the
Error()method, so the type does not satisfy theerrorinterface. - Using pointer receiver vs value receiver inconsistently, which can cause interface mismatch.
- Returning the struct instead of the interface, which can cause unexpected behavior in comparisons.
Always implement Error() and return the error as the error interface type.
go
type BadError struct { Msg string } // Missing Error() method - this will NOT work as an error // Correct way: func (e BadError) Error() string { return e.Msg }
Quick Reference
Summary tips for custom errors in Go:
- Define a struct to hold error details.
- Implement
Error() stringmethod. - Return your error as the
errorinterface. - Use value or pointer receiver consistently.
- Use custom errors to add context or extra info.
Key Takeaways
Create a struct and implement the Error() string method to make a custom error type.
Return your custom error as the error interface to use it like built-in errors.
Consistently use value or pointer receivers for the Error() method to avoid interface issues.
Custom errors let you add extra information beyond simple error messages.
Always check errors returned as the error interface in your code.