Home >Backend Development >Golang >How Do I Effectively Compare and Handle Errors in Go, Unlike Java\'s GetMessage()?

How Do I Effectively Compare and Handle Errors in Go, Unlike Java\'s GetMessage()?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-25 21:09:11207browse

How Do I Effectively Compare and Handle Errors in Go, Unlike Java's GetMessage()?

Comparing Error Messages in Go

In Java, you can use GetMessage() to retrieve the error message from an Exception. However, in Go, there is no equivalent method defined for the error type. Instead, custom error handling techniques must be employed.

Custom Error Handling

One approach is to define a package-level variable to represent the specific error message you want to check for. For instance:

var errExample = errors.New("this is an example")

When returning errors, you can use this variable instead of a generic error string:

if err := some_package.DoSomething(); err != nil {
    if err == errExample {
        // handle it however.
    }
}

Exporting the Error Variable

If code outside the package needs to access the error, you can export the variable using a capital letter:

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

This allows you to compare the error against the exported variable:

if err == somepackage.ErrExample {
    // handle it
}

Examples

  • Absolute File Path: os.ErrNotExist
  • HTTP Error: net/http.ErrServerClosed
  • Database Error: database/sql.ErrNoRows

Pitfall: Avoid String Comparison

Resist the temptation to compare against the string returned by the error's Error() method. This can result in brittle code. For instance:

if err.Error() == "this is an example" {
    // this is not recommended
}

Instead, use the custom error handling approach outlined above.

The above is the detailed content of How Do I Effectively Compare and Handle Errors in Go, Unlike Java\'s GetMessage()?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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