Home > Net >  How to know variable name adhering to go error
How to know variable name adhering to go error

Time:11-16

When working with go there is a pattern used to define errors and handle them in a (to me) very peculiar way. Often errors are declared like ErrorSomethingWentWrong = errors.New("Just an example!"). You can use errors.Is(err, ErrorSomethingWentWrong) to catch that specific error. The Is function can do this by comparing the pointers. But in order to make the comparison I need to know which variable name is used to define the errorString so I can use errors.Is to catch it.

For example:

ErrorSomethingWentWrong = errors.New("Just an example!")
func DoSomething() (*Something, error) {
    return nil, ErrorSomethingWentWrong
}

I know a error is returned with the string "Just an example!" But I don't know it has the variable name ErrorSomethingWentWrong:

func checkError() {
    if errors.Is(err, ErrorSomethingWentWrong){ // how to know this???
       //handle error
    }
}

When I use errors.Is(err, ErrorSomethingWentWrong) I can catch this error and handle it. When using debugging I can't see that the errorString represents the ErrorSomethingWentWrong variable. But when I don't know that the variable name was ErrorSomethingWentWrong I need to reverse engineer the code or read the docs to know which error is returned.

enter image description here

So how can you know using debugging or reflection to retrieve the error variable name?

CodePudding user response:

If I understand correctly, this is your scenario:

You are receiving an error from a package, and there is no documentation to provide you with the errors you should be handling. You are debugging, and see an errors.errorString, but don't know if there is a global and public error value that you can compare to.

Unfortunately, this is a value and the debugger can't tell you if this is a global variable or if so which one, because you don't receive a variable, only a value.

You can:

  • read through the source code of the package you are calling and see which errors are being returned and how to handle them
  • search the source code for the text in the error string, this could help you pinpoint where the error is defined or created.

If it turns out the specific error you wish to handle is not defined globally (and re-writing the package is not feasible for your case), so you can't handle it. This can happen if somebody uses errors.New inside a function (bad practice). Then you can also try these:

func handleError(err error) {
    if err.Error() == "full error string" {}

    if strings.Contains(err.Error(), "partial error string") {}
}

But those are both ugly imho.

TL;DR It's not possible, you have to read the source code.

  • Related