Just started using Golang. I think that it is idiomatic to declare an error variable and use it in your error structure to determine what went wrong, as is done in strconv.go. There, ErrRange
and ErrSyntax
is declared, and when appropriate, references to those are stored in NumError
structs when they return. I think that the reason is because then the address of the reference to the error stored in NumError
can be compared with the ErrRange
and ErrSyntax
variables to determine which type of error was returned.
Are there "standard" such declared error types? In Java, for example, you have things like java.lang.IllegalArgumentException
. Is there, for instance, ErrArgument
or ErrUnsupportedOperation
that I can use in my own code instead of creating new error variables that mean the same thing every time?
There are a few common idiomatic ways for a package author to make error returns.
Fixed error variables, usually named
Err…
Error types, usually named
…Error
Ad hoc
errors.New
values as needed.Using errors defined in the standard packages. Usually limited to a small set such as
io.EOF
; in most cases it's better to create your own via method 1 above.Note that sometimes when implementing an interface (such as a
Read
method to become anio.Reader
) it is best to use matching errors (or "required" by the specification of the interface).Making an interface such as
net.Error
:Often you'll use a mix of all these ways.
The first, second, and fifth are preferred if you think any user of your package will ever want to test for specific errors. They allow things like:
The fifth way (which is just an extension of the second) allows checking the error for behaviour/type like so:
The problem with the third way is it leaves no sane way for a user of the package to test for it. (Testing the contents of the string returned by
err.Error()
isn't a great idea). However, it's fine for the errors that you don't ever expect anyone to want to test for.Further reading:
As you have seen, there are specific errors that specific packages use. For example, in the database/sql package, they define:
So if you do
QueryRow
(which defers the error untilScan
), and thenScan
, you can doos/exec has
var ErrNotFound = errors.New("executable file not found in $PATH")
encoding/json has a
type UnmarshalTypeError
which is just a type that implements theerror
interface.So no, while there is no "set of standard errors", you can (and most likely should) have specific error variables that you reuse.
You could have your own errorMsgs package that you use, where you can reuse common errors:
No, there aren't. Just provide intelligible errors instead of generic ones. What information does a IllegalArgument transport? Not much, not enough.