I have an error value which when printed on console gives me Token is expired
How can I compare it with a specific error value? I tried this but it did not work:
if err == errors.New("Token is expired") {
log.Printf("Unauthorised: %s\n", err)
}
Declaring an error, and comparing it with '
==
' (as inerr == myPkg.ErrTokenExpired
) is no longer the best practice with Go 1.13 (Q3 2019)The release notes mentions:
So the Error Value FAQ explains:
This answer is for Go 1.12 and earlier releases.
Define an error value in a library
Do not create errors with
errors.New
anywhere in the code but return the predefined value whenever error occurs and then you can do the following:See
io
package errors for reference.This can be improved by adding methods to hide the check implementation and make the client code more immune to changes in
fruits
package.See
os
package errors for reference.It's idiomatic for packages to export error variables that they use so others can compare against them.
E.g. If an error would came from a package named myPkg and was defined as:
You could compare the errors directly as:
If the errors come from a third party package and that doesn't use exported error variables then what you can do is simply to compare against the string you get from err.Error() but be careful with this approach as changing an Error string might not be released in a major version and would break your business logic.
Try
Or create your own error by implementing the error interface.
The error type is an interface type. An error variable represents any value that can describe itself as a string. Here is the interface's declaration:
The most commonly-used error implementation is the errors package's unexported errorString type:
See this working code output (The Go Playground):
output:
Also see: Comparison operators
So:
1- You may use
Error()
, like this working code (The Go Playground):output:
2- Also you may compare it with
nil
, like this working code (The Go Playground):output:
3- Also you may compare it with exact same error, like this working code
(The Go Playground):
output:
ref: https://blog.golang.org/error-handling-and-go