4 ms·
You should read Dave's presentation again. Asserting for a type is the wrong way to do it, your library should instead provide a helper for the specific parsing
by rakoo 10y ago
You should read Dave's presentation again. Asserting for a type is the wrong way to do it, your library should instead provide a helper for the specific parsing you want to do.
So if you want to know if this error is temporary, you should have this, inside the net package:
func IsTemporary(err error) bool {
// specific parsing
}
Similarly, if you really want an error code:
func ErrorCode(err error) int {
// a type assertion, which is fine because we're inside the net package
v, ok := err.(ErrorWithStatusCode)
if ok {
return v.ErrorCode
}
}
(Note that in the standard net/http package, the result of an http call is inside the result, never in the error that is returned, whatever the status of the http call is)
Basically your package should give all tools so that callers can take a decision without knowing about internals of the package. Knowing the exact error code is probably not what a caller wants; what they probably want to know is whether the error is temporary or fatal, if they can retry with a chance of success, if they can take counter-measures and if they can't alert the user.
- fauigerzigerk 10y agoI think I have read everything Dave Cheney has ever written about errors. But you misunderstand what I'm saying. The standard library is already littered with error values defined on the package level. Many third party packages emulate that approach. Once you have done that in package, there is no way to change it. You cannot add function call specific data to an error after the fact. There is no way to implement an IsTemporary(error) function once you have clients that compare any returned error to a package level singleton using ==. >Knowing the exact error code is probably not what a caller wants I had that need many times. For instance, I needed to get the SQLSTATE from database errors. There is a huge number of SQLSTATE codes and interpreting/classifying them can't be the job of a data access package or even a DBMS specific driver library. Also, how would a networking package know what I consider temporary? Some protocols like HTTP specify some errors to be temporary, but that may not coincide with what I'm willing to retry or not retry.