The errors.New function in Go is used to create a new error with a specified message. This function is part of the errors package and is typically used to generate simple error messages in Go programs.
Syntax
func New(text string) error
Parameters:
- text: A string that represents the error message.
Returns:
- error: Returns an error object containing the specified message.
Example Usage
Basic Example
This example demonstrates how to use errors.New to create a simple error with a custom message.
package main
import (
	"errors"
	"fmt"
)
func main() {
	err := errors.New("something went wrong")
	if err != nil {
		fmt.Println("Error:", err)
	}
}
Output:
Error: something went wrong
Using errors.New in a Function
You can use errors.New to return errors from functions when something goes wrong during execution.
Example
package main
import (
	"errors"
	"fmt"
)
func divide(a, b int) (int, error) {
	if b == 0 {
		return 0, errors.New("division 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: division by zero
Combining errors.New with Other Error Handling Techniques
In more complex applications, you may want to combine errors.New with other error-handling techniques, such as wrapping errors or adding context.
Example
package main
import (
	"errors"
	"fmt"
)
func readFile(filename string) error {
	return errors.New("failed to read file: " + filename)
}
func main() {
	err := readFile("example.txt")
	if err != nil {
		fmt.Println("Error:", err)
	}
}
Output:
Error: failed to read file: example.txt
Using errors.New for Constant Errors
In some cases, you might want to define constant errors that can be reused throughout your program.
Example
package main
import (
	"errors"
	"fmt"
)
var ErrNotFound = errors.New("item not found")
func findItem(id int) error {
	// Simulate an item not found situation
	return ErrNotFound
}
func main() {
	err := findItem(1)
	if err == ErrNotFound {
		fmt.Println("Error:", err)
	}
}
Output:
Error: item not found
Conclusion
The errors.New function in Go is used for creating error messages in your applications. It’s especially useful for generating straightforward error messages when something goes wrong. By leveraging errors.New, you can easily create and return error objects, making your error handling more consistent and easier to manage. Whether you’re building simple applications or complex systems, errors.New is a fundamental part of Go’s error-handling toolkit.