How to handle custom type errors in Golang?

WBOY
Release: 2024-06-05 12:47:56
Original
950 people have browsed it

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.

如何处理 Golang 中自定义类型的错误?

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-inerrors.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) }
Copy after login

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 useerrortype assertionsto 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 }
Copy after login

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 }
Copy after login

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) // 输出:数字必须为非负数 } }
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!