3 ms·
Let’s hope Go never gets try/catch exceptions
by thefounder 2y ago
Let’s hope Go never gets try/catch exceptions
- randomdata 2y agofunc try(fn func()) { fn() } func catch(fn func(any)) { if v := recover(); v != nil { fn(v) } } func throw(v any) { panic(v) } func fail() { throw("Bad things have happened") } func main() { try(func() { defer catch(func(v any) { fmt.Println(v) }) fail() }) } Sorry.
- rnmmrnm 2y agothe day the go codebase throws random panics is the day I quit the company.
- randomdata 2y agoSo you quit the day encoding/json was written?
- kubanczyk 2y agoYou are probably thinking about (proto)reflect.
- randomdata 2y agoNo, I am thinking of encoding/json. It uses Go's exception handlers to pass errors around, much like the code above.
- SleekoNiko 2y agoForgive me as I'm not experienced in Go. I had a look at the API reference for encoding/json[1] and performed a (very hasty) search on the source code[2]. The API reference doesn't state that panics are a part of the expected error interface, and the source code references seem to be using panics as a way to validate invariants. Is that what you're referring to? I'm not entirely sure if the panics are _just_ for sanity, or if input truly can cause a panic. If it's the latter, then I agree - yikes. [1] - https://pkg.go.dev/encoding/json https://pkg.go.dev/encoding/json [2] - https://cs.opensource.google/search?q=panic&sq=&ss=go%2Fgo:src%2Fencoding%2Fjson%2F https://cs.opensource.google/search?q=panic&sq=&ss=go%2Fgo:s...
- randomdata 2y agoThe use does not transcend package boundaries, but you will find its use within the package itself, which is within the Go codebase spoken of earlier.
- rnmmrnm 2y agoyou wrap those properly. believe me waking up in the middle of the night because someone abused panic to throw state around, end up being called from a new goroutine, just enough to crash the entire pod, sucks even more.
- chx 2y agoThere is evil in this world and then there's ... this :D
- marcus_holmes 2y agoESBuild, one of my favourite Go projects, uses panics to handle try/catch exceptions. The syscall/js package [0] throws panics if something goes wrong, rather than returning errors. Go already has try/catch exceptions. We just don't use them most of the time because they're a really bad way of handling errors. [0] https://pkg.go.dev/syscall/js https://pkg.go.dev/syscall/js