How to Use errors.New in Go: Simple Error Creation
In Go, use
errors.New to create a new error with a descriptive message. It returns an error type that you can return or handle in your functions.Syntax
The errors.New function takes a single string argument that describes the error message. It returns a value of type error which can be used to indicate an error condition.
errors.New("message"): creates a new error with the given message.- The returned error implements the
errorinterface.
go
import "errors" func example() error { return errors.New("something went wrong") }
Example
This example shows how to create and check an error using errors.New. The function divide returns an error if the divisor is zero.
go
package main import ( "errors" "fmt" ) func divide(a, b int) (int, error) { if b == 0 { return 0, errors.New("cannot divide by zero") } return a / b, nil } func main() { result, err := divide(10, 0) if err != nil { fmt.Println("Error:", err) return } fmt.Println("Result:", result) }
Output
Error: cannot divide by zero
Common Pitfalls
Common mistakes when using errors.New include:
- Not checking the error returned by a function, which can cause unexpected behavior.
- Using
errors.Newrepeatedly for the same error message instead of defining a package-level error variable. - Confusing
errors.Newwith formatting functions likefmt.Errorfwhich allow formatted error messages.
go
package main import ( "errors" "fmt" ) // Wrong: Not checking error func wrongDivide(a, b int) int { result, _ := divide(a, b) // ignoring error return result } func divide(a, b int) (int, error) { if b == 0 { return 0, errors.New("cannot divide by zero") } return a / b, nil } func main() { fmt.Println("Wrong divide result:", wrongDivide(10, 0)) }
Output
Wrong divide result: 0
Quick Reference
Tips for using errors.New effectively:
- Use
errors.Newfor simple static error messages. - For dynamic messages, prefer
fmt.Errorf. - Always check errors returned from functions.
- Define reusable error variables for common errors.
Key Takeaways
Use errors.New to create simple error messages in Go.
Always check the error returned by functions to handle failures.
For formatted error messages, use fmt.Errorf instead of errors.New.
Define package-level error variables for repeated error messages.
Ignoring errors can lead to bugs and unexpected program behavior.