Yes, you can define custom error types in Go by creating a structure that implements the error interface and providing the Error() method to return an error message. Custom error types can be created using the errors.New function or a custom type. In practice, custom error types can provide more specific and meaningful error messages, enhancing the usability and maintainability of the application.
In Go, errors are usually represented through the built-in error
interface. However, sometimes it is necessary to define custom application-specific error types. This article describes how to create a custom error type and provides a practical case.
Create a custom error type
Custom error types can be implemented by creating a structure that implements the error
interface.
type MyError struct { msg string } func (e *MyError) Error() string { return e.msg }
Error() string
method returns an error message, which is a requirement of the error
interface.
Usage
Custom error types can be created using the errors.New
function, which accepts a string parameter as the error message.
err := errors.New("my error message")
Alternatively, you can use a custom type to create an error:
err := &MyError{msg: "my error message"}
Practical case
Scenario: Verify user input age.
Error type:
type InvalidAgeError struct { msg string } func (e *InvalidAgeError) Error() string { return e.msg }
Error checking code:
func ValidateAge(age int) error { if age < 18 { return &InvalidAgeError{msg: "年龄必须大于或等于 18"} } return nil }
Error handling code:
age := 15 err := ValidateAge(age) if err != nil { fmt.Println("错误:", err) } else { fmt.Println("年龄已验证") }
Output:
错误:年龄必须大于或等于 18
Custom error types provide more specific and meaningful error messages, which helps improve the usability and maintainability of your application.
The above is the detailed content of Custom golang function error type. For more information, please follow other related articles on the PHP Chinese website!