9 ms·
Most Go criticism I've seen on error handling has been “if you are going to use errors-as-values, sum types and pattern matching were the well established appro
by dragonwriter 3y ago
Most Go criticism I've seen on error handling has been “if you are going to use errors-as-values, sum types and pattern matching were the well established approach to that when Go was created and multivalued returns when only one value is usually going to be meaningful at a time is both logically and ergonomically worse” not “don't use errors as values”.
- teaearlgraycold 3y agoBasically - use Rust instead.
- danesparza 3y agoWhy? This doesn't look particularly more or less friendly in Rust than in any other programming language: https://doc.rust-lang.org/book/ch09-00-error-handling.html https://doc.rust-lang.org/book/ch09-00-error-handling.html
- LelouBil 3y agoA lot of common error handling patterns are expressed more effecively in Rust. For bubbling up errors you have the ? operator, then on results you have map, map_err, and, ok_and...
- ColonelPhantom 3y agoAside from the other reply which points out that common idioms have useful shorthands like ?, Rust's type system is also error-aware. Rust errors are actual sum types (either Ok(T) or Err(E)), while Go just uses multiple return/tuples to return (value, nil) or (nil, error). This means that in Rust, you are forced to handle errors (well, unless you don't care about the return value, but then the compiler still gives a warning). This means it is harder to make a mistake with error checking.
- monocasa 3y agoIt also enforces the lack of weird anti patterns like some functions in go that will return a significant value in the first return value while also returning non nil in the error, with a snarky comment in the docs about why this actually makes sense in this case.
- beautron 3y agoI don't consider this an anti-pattern, but part of the flexibility gained by Go's lightweight approach to error handling. I believe Go was even designed with this use case in mind (the standard library uses it in many places, and I don't consider their documentation about it "snarky"). Sometimes you want to return a partial result along with an error. Go's idiom of returning multiple values, with the final value being an error, allows this situation to be easily supported.
- monocasa 3y agoExcept in the case I'm talking about, there was a resource to be reclaimed, the GC didn't cover it. And if you wanted to do that in rust, that's a valid thing too, either as using a tuple instead of a sum type, or a tuple in the Err side of a result. You can describe what you're trying to do simply with the function signature.
- lmm 3y ago> Sometimes you want to return a partial result along with an error. Sometimes you do, and there are types that represents that. Having a single type that is almost always used a certain way but occasionally used subtly differently is a trap waiting to bite you.
- beautron 3y agoI've been using Go for almost a decade, and I don't recall this ever biting me. It doesn't feel like a trap. Go has a convention of documenting each function with a comment (which is adhered to by the standard library, my own code, and any other code I'd consider worthy of depending on). So when I think this subtlety matters, I check the documentation. Usually I don't care either way: When I get a non-nil error, I typically don't care about the other result (whether partial or the zero value). The distinction rarely matters in practice (and when it does, the documentation is there). I think this simplicity is the right tradeoff (vs. being burdened with more types to think about).
- rtpg 3y agoThe question-mark shorthand (?) basically does what the blog post is describing, and makes a lot of this stuff straightforward. There _is_ some futzing that sometimes have to happen due to various operations' Result types using incompatible Error types. That's just a thing that has to be dealt with.
- mcronce 3y agoYeah, but that futzing typically happens separately near the "outer" error type's declaration - and when it doesn't, a concise .map_err() often does the job. It's also often taken care of by a sort thiserror macro invocation per "inner" type. There are obviously more complex error setups, but this covers the vast majority IME
- rtpg 3y agoI get why it's like this but I have often found that most of the time code ends up bailing by using a conversion into `String` quite quickly, leading to everything being stringified anyways. I get why this is, but it does make me miss the Python Exception model of "there's ~15 base exception types. One of them is probably good enough for you". One could point out that the arguments are usually "just" strings there too, but at least there's some conventions. I understand Rust's philosophy, I just find it annoying.
- mcronce 3y agoI haven't experienced that at all. Any of the codebases I've worked in - both proprietary and open-source - have converted errors to strings when it becomes necessary: When presenting it to a user, whether that means logging or placing it in an HTTP response body, etc.
- _AzMoo 3y agoI find Rust's question mark shorthand and the resulting futzing you're talking about adds a lot more cognitive load for me than Go's verbose if err conventions. I think more than anything this kind of syntactical discussion is just very subjective.
- flakes 3y agoI know this is a meme, but after writing a lot of Go, and now finally trying out Rust for a new project, I’m quickly coming to this conclusion.
- dgunay 3y agoI love Rust but it is accidentally in the position of trying to serve two disparate camps of people. Developers who just want a modern ML-ish language with good tooling and some actual lessons learned from PL theory, and developers who need near-total control over the hardware but are tired of working with C & C++ and manually solving decades-old problems with memory safety. The former are a very large audience, but have to deal with requirements imposed by the latter which are irrelevant for their use case.
- jrop 3y agoThis a million times. I love working with Rust because it's - from my point of view - an ML language disguised in C-syntax (with a package manager and unit testing etc. etc). Most of the time I'd be served well by a GC version of Rust.
- carterschonwald 3y agoRust with gc by default and higher kinded traits being sane and supported would be my fave
- threeseed 3y ago> Most of the time I'd be served well by a GC version of Rust You've just described Scala which inspired many of Rust's features.
- pjmlp 3y agoThat would be Standard ML, Haskell and OCaml, not Scala.
- selfmodruntime 3y ago
- dragonwriter 3y agoRust is definitely a near-contemporary of Go that made the sum-type-and-pattern-matching choice, yes, though outside of that difference the focus of the languages is very different, so it might always be the right choice if Go was but for error handling ergonomics.
- teaearlgraycold 3y agoI need to say the Go stdlib is really excellent.
- pjmlp 3y agoQuite lacking when compared against Java, .NET, Python standard libraries.
- teaearlgraycold 3y agoEh. I’d say it’s better than Python’s. I’m not familiar enough with Java or .NET to talk about them.
- monocasa 3y agoOr one of the ML variants if you prefer a GCed language. F#, OCaml, SML, were great choices when go was written. Reason has been added since.
- pizzafeelsright 3y agoMy frustration, possibly perhaps how I'm coding, is wrapping every instruction on an error wrapper and then I've got twenty if not an error do the next thing. I code solo, so I'm not sure how others do it. The alternative is to have twenty methods? I build a data structure, modify its state in a dozen ways and then return it to the caller.
- marcus_holmes 3y agoI like Go's error handling. Yes, I know that puts me in a special category of coder. Reasons: - It's simple and easy to understand. There's no hidden complexity, no magic, no gotchas. Nothing is going to surprise me about it. - It's a very readable cadence. Do the thing, check the error, do the thing, check the error, do the thing, check the error. Once you get used to the error checks it's extremely readable. - Despite all the extra characters the actual mental load of the error checks is tiny. Yes it's more typing, but the hard bit about code is thinking not typing, and it doesn't make more thinking. - If I have to do something special with the error, it's easy. There's no incentive to handle this error just like the rest, or ignore it and let the exception handler catch it. If this error needs (for example) extra logging then I can just put it in there for this error check, no hassle. - It's pretty much standard across all Go code. If I have to deal with someone else's code, I can expect the same cadence, the same simplicity, the same readable pattern of error checks. One of the great things about Go is that it is opinionated about stuff like this.
- lmm 3y ago> - Despite all the extra characters the actual mental load of the error checks is tiny. Yes it's more typing, but the hard bit about code is thinking not typing, and it doesn't make more thinking. The hard part is understanding the existing code. The more cluttered and verbose the code is, the harder that is. Go's boilerplate if err != nil return err, nil becomes something that your eyes just skim over - which is fine right up until you have some code that's doing something similar but not the same, and don't even notice.
- 3y ago
- 015a 3y agoI'll use this opportunity to share my personal criticism on Go error handling; this right here. https://go.dev/play/p/WbGeW8wSu0X https://go.dev/play/p/WbGeW8wSu0X (Ignore the obvious SQL injection issues in that query, thx :) It takes a lot to make me mad, but this inane behavior manages it. This behavior, singularly, makes it nearly impossible to achieve higher levels of ergonomic safety on the types of errors functions can return. You basically always have to just return the `error` type, and require callers to do runtime reflection. And this can rear its ugly head all the time. You've got deep functions that are super specific and know exactly what kinds of errors they can return. You've got higher-layered functions that call lots of things that all return different error types, so those may just return `error`. Turns out; they all just have to return `error`, because if you make them more specific, at the freakin TYPE DEFINITION, a segment of the syntax that other sane languages would say is "compiled away" and "not relevant to runtime behavior", you lose any ability to guarantee nil comparisons will work the way higher-level callers expect. https://go.dev/play/p/fb0e_4loDBf https://go.dev/play/p/fb0e_4loDBf Its a problem in any situation where a function broadens the type of a struct pointer its returning to an interface. Its just most commonly encountered with errors, because you can't just return `DatabaseError` there, because the zero-value is non-nil and everyone checks errors with `if err != nil`. The internal Go style guide of a billion dollar tech company every single person reading this has heard of reads: Never return pointers to structs designed to be used as errors. Its a significant, real problem. Its antithetical to any reasonable understanding of how this code should work. Its antithetical to even unreasonable understandings. Blog posts which explain it start with "this makes sense when you understand how reflection works on interface-fulfilling pointer values" then launch into a twenty paragraph graduate thesis as if Go wasn't explicitly designed to help fresh-out-of-college engineers write productive and performant code for Google. I like Go; but their recent statement that Go will never break backward compatibility genuinely scares me because I'm not sure they can fix this without breaking existing code; which means it may never get fixed. I'm doubtful the designers even consider it a bug. Just... ugh.
- randomdata 3y ago> Its a significant, real problem. It's a contrived problem, at least. In reality, your code is going to look more like: func GetUserByID(id string) (string, error) { s, err := QueryDatabase(fmt.Sprintf("select * from users where id = %v", id)) if err != nil { // Do something with the error, returning a new error if necessary. return "", someNewErr } return s, nil } The callers of GetUserByID have absolutely no concern for the implementation details of QueryDatabase. When requirements change and you replace QueryDatabase with QueryWebService, callers expect to still get the same errors back, not HTTP errors all of a sudden when the code was previously getting MySQL errors. That would be plain horrible API design. So, you wouldn't actually ever encounter this particular issue in practice (assuming nobody hates you).