I read the section from the Go FAQ about error handling and I have a question about it. This section states that it is a good practice for functions that return an error to always return error, and not concrete error.
As an example, os.Open
is given, which returns error, although in fact it is always *os.PathError
. This approach is insisted because of the fact that it helps to ensure that error is created correctly. “Correctly” means not getting into a trap of a gotcha, related to the fact that error is an interface and therefore that line return p
, where p is *MyError
will actually always return a non-nil error interface.
I don’t understand why this kind of code is considered bad. It seems strange to me that function os.Open
returns error by signature, but in fact it is always returns *os.PathError
, which is stated for some reason in the docs, but not in the function signature.
I do not understand the motivation for this approach. Could someone please explain to me why it is done this way?