Home >Backend Development >Golang >How to handle custom type errors in Golang?
Creating custom error types allows you to handle domain-specific errors in Golang. After creating an error type, you can use error assertions to check if the error type matches a custom error type. If there is a match, you can access the custom error message. Otherwise, handle other types of errors.
How to handle custom type errors in Golang
Creating custom error types in Golang is to define specific domain errors good idea. This allows you to create errors that contain additional information about the error.
Create a custom error type
To create a custom error type, you can use the built-in errors.New()
function:
package errors import "fmt" type MyError struct { msg string } func New(msg string) *MyError { return &MyError{msg: msg} } func (m *MyError) Error() string { return fmt.Sprintf("自定义错误:%s", m.msg) }
Error()
method returns an error message. It should be the only method that implements the error interface, i.e. it should return a string type message.
Handling custom errors
Once you create a custom error type, you can use errortype assertions
to check for errors:
func process() error { // 调用可能有错误的方法 if err := doSomething(); err != nil { if me, ok := err.(*MyError); ok { // 处理自定义错误 fmt.Println(me.msg) } else { // 处理其他类型的错误 return err } } return nil }
Practical Case
The following is an example of a function that may throw a custom error when converting a number to a string:
func convertToString(num int) (string, error) { if num < 0 { return "", errors.New("数字必须为非负数") } return strconv.Itoa(num), nil }
When calling this function, You can use error assertions to handle custom errors:
result, err := convertToString(-1) if err != nil { if me, ok := err.(*errors.MyError); ok { fmt.Println(me.msg) // 输出:数字必须为非负数 } }
The above is the detailed content of How to handle custom type errors in Golang?. For more information, please follow other related articles on the PHP Chinese website!