4 ms·
You’ll find some libraries do this for you, such as HTTP servers. They do this because if your server code makes a mistake such as accessing a nil pointer, a s
by lawrjone 3y ago
You’ll find some libraries do this for you, such as HTTP servers.
They do this because if your server code makes a mistake such as accessing a nil pointer, a segfault or panic would bring down the entire process. That’s why you want to recover(), to avoid a your process dying.
- kubanczyk 3y ago> They do this because if your server code makes a mistake This is neither good or best practice. My take: - Know that there are simple-mistake panics, and internal-state-just-went-bonkers panics. For the latter, you can guess the boundary of impact (one request, one connection, one job, one userID, one process, ...) but exit(1) is much more reliable than guessing. - Tests can easily catch simple mistakes like accessing a nil pointer. - Know that the kind of programmer who does not care about simple tests, will also not care about concurrency bugs which introduce the more dangerous types of state corruption. This corruption would likely be not limited to a single request. Good luck to frameworks who assume that nothing bad would happen if they ignore a panic and continue serving more requests.
- heywhatupboys 3y ago> - Tests can easily catch simple mistakes like accessing a nil pointer. no they can't . this is exactly what is hard to test for, complex state that can occur by some combination of many variables on many values
- lawrjone 3y agoRespectfully, this is a really bad take. And one that flies in the face of the Go stdlib, given the default HTTP server will catch panics for you by default.
- jrockway 3y agoI mean, net/http does it. That's the standard library. A go convention that I've made up, or that is perhaps a real one, is to always look at the standard library for guidance on how to write Go. net/http suffers a little bit from being a very early library and thus you might not want to emulate its API surface. But in general, the Go team thought "you know what every HTTP handler in Go needs? recovery from panics" and that is worth some weight when considering your own design. I would personally recommend fuzz testing your code, including HTTP handlers. The more panics you find in development, the fewer customers you lose from panics in production. Remember that recovering from a panic in an HTTP handler still means your user's request didn't get processed. They are not happy about that, even if your program can still service other users.
- deleted 3y ago[deleted]