2 ms·
Correct me if I'm wrong, but the Error interface means you can display the error as a string, but you don't have to? Like the err.Error() is idiomatic if you ju
by dematz 9mo ago
Correct me if I'm wrong, but the Error interface means you can display the error as a string, but you don't have to? Like the err.Error() is idiomatic if you just want to display something, but you could also use the error itself
https://pkg.go.dev/errors#As https://pkg.go.dev/errors#As
here's an example that uses a field from your blog example error type: https://go.dev/play/p/SoVrnfXfzZy https://go.dev/play/p/SoVrnfXfzZy
Also "In Go, errors are values. They just aren’t particularly useful values"
...sometimes user mistakes are due to the language being too complicated, maybe for no benefit, but I don't think that's the case here. It's a very good thing that you can just slap .Error() on any error to print it quickly, and not too crazy complex to say an error can be any normal type that you can use, as long as it also can print Error()
- MobiusHorizons 9mo agoMy guess is that the author hasn’t fully frocked how go interfaces work yet. Go errors implement the error interface, but that just makes them interoperable, it doesn’t mean that’s all they are.
- benrazdev 9mo agoCorrect me if I am wrong, but does it not mean that they are type-erased though? The whole point of returning an interface is to perform type-erasure. If I have struct S { X int } func (s *S) Error() string { ... } but I return it as an error: func DoStuff() error Then all the caller gets is an error interface. Without downcasting (`.(T)`/`errors.As`), you can only compare it to other instances (if the library author provided them) or see the string representation.
- MobiusHorizons 9mo agoYes, that's correct. The interface limits what guarantees the caller has about the type without runtime introspection. I don't think that really makes it any harder to handle expected error conditions though, since type assertions return a boolean. eg: if myErr, ok := err.(MyError); ok { // handle MyError case } ... But you should always expect that there could be errors you don't expect to exhaustively handle with special logic.