Home > Backend Development > Golang > How Can I Reliably Compare Errors in Go?

How Can I Reliably Compare Errors in Go?

Mary-Kate Olsen
Release: 2024-11-27 13:46:11
Original
610 people have browsed it

How Can I Reliably Compare Errors in Go?

Comparing Error Messages in Go

In Go, errors are simply values that implement the error interface. This means that errors can be compared using the standard equality operators (== and !=). However, it is generally not recommended to compare errors by their string representation returned by the Error() method. This is because the string representation can change over time, which can make your code brittle.

A more reliable way to compare errors is to use a package-level variable that stores the expected error. This variable can be used to compare against the error returned by a function. For example:

package mypkg

import (
    "errors"
)

// ErrExample is an example error.
var ErrExample = errors.New("this is an example")

// DoSomething returns an error if something goes wrong.
func DoSomething() error {
    // ...

    // If something goes wrong, return the error.
    return ErrExample
}
Copy after login

To compare against the error returned by DoSomething(), you can use the following code:

if err := DoSomething(); err != nil {
    // Handle the error.
}
Copy after login

If the error returned by DoSomething() is equal to ErrExample, then the if statement will be executed.

You can also export the package-level variable if code outside the package needs to access the error. For example:

package mypkg

import (
    "errors"
)

// ErrExample is an example error.
var ErrExample = errors.New("this is an example")

// Export the error.
var ErrExample = ErrExample
Copy after login

To use the exported error, you can use the following code:

if err := somepackage.DoSomething(); err != nil {
    // Handle the error.
}
Copy after login

If the error returned by somepackage.DoSomething() is equal to mypkg.ErrExample, then the if statement will be executed.

By using a package-level variable to compare errors, you can make your code more reliable and less brittle.

The above is the detailed content of How Can I Reliably Compare Errors in Go?. For more information, please follow other related articles on the PHP Chinese website!

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 Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template