by blindriver · 1y ago · 0 comments
Maybe passing it up the stack is the best way to handle it, but also maybe it’s better to handle it somewhere in the middle.
The thing that always happens with exceptions in API projects I’ve worked on, is that exceptions can come from any level of the stack, then by default it skips everything in the middle, and the controller has default handlers for what to do in case of an exception.
If there are exceptions you didn’t know existed because of some library or just complex code with dozens of possible exceptions? They still end up being handled in your controller. You need to know exactly what exceptions could happen at every level of the stack, and how to handle it, otherwise everything just short circuits.
With the go errors, you only need to know “did this function call work? If not, then what?”
However, I strongly prefer rust error handling to Go.
go:
(res, err) := foo()
if err != nil
return err
(res, err) := bar(res)
if err != …
Equivalent rust: let res = bar(foo)?)?;
I think go should add the ? sigil or something equivalently terse.Ignoring all the extra keystrokes, I write “if err == nil” about 1% of the time, and then spend 30 minutes debugging it. That typo is not possible in idiomatic rust.
In Rust, there are cases where I have seen at least 8 consecutive symbols. Not a fan of that.
If someone saw "go funcName()" for the first time, would they know how it worked without looking it up?
I hear people say this frequently, but don't ever hear people actually state the case.
My experience is that particularly for web back-end exceptions have been incredibly useful, but I'm interested in the counter view.
let res = bar(foo());
(I think you meant: let res = bar(foo()?)?;I'm curious because I've never felt it being onerous nor felt like there was much friction. Perhaps because I've primarily built web applications and web APIs, it's very common to simply let the exception bubble up to global middleware and handle it at a single point (log, wrap/transform). Then most of the code doesn't really care about exceptions.
The only case where I might add explicit exception handling probably falls into a handful of use cases when there is a desire to a) retry, b) log some local data at the site of failure, c) perform earlier transform before rethrowing up, d) some cleanup, e) discard/ignore it because the exception doesn't matter.
If you need to handle errors, you quickly get into extremely complicated control flow that you now have to test:
// all functions can throw, return nil or not.
// All require cleanup.
try {
a = f();
b = a.g();
} catch(e) {
c = h();
} finally {
if a cleanup_a() // can throw
if b cleanup_b() // null check doesn’t suffice…
if c cleanup_c()
}
Try mapping all the paths through that mess. It’s 6 lines of code. 4 paths can get into the catch block. 8 can get to finally. Finally multiplies that out by some annoying factor.But in gui applications and servers, you will need to catch and report the error in some intermediate boundary, not exit the application. That's where go falls short.
def bracket[A, T](ctor: () -> A, next: (a: A) -> T): T =
val a = ctor();
try { return next(a) } finally { a.dispose() }Here, the lowest level IO error (which could be quite unhelpful, because at best it can tell you the name of the file, but not WHY it’s being opened) is wrapped with the exact type of the file being opened (a user database) and why the database is being opened (some part of processing ‘foo’, could even generate better error message here).
Although this is a bit of work (but in the grand scheme of things, not that much), it generates much better debugging info than a stack trace in a lot of situations, especially for non-transient errors because you can annotate things with method arguments.
I think the common complaint of ‘if err != nil { return err }’ is generally not the case because well-written Go will usually prepend context to why the operation was being performed.
> Most of my code will annotate a lower error with the context of the operation that was happening.
This is easy to solve with chained exceptions to add context. > it generates much better debugging info than a stack trace in a lot of situations, especially for non-transient errors because you can annotate things with method arguments.
You cannot add method args to an exception message? I am confused.When we were rewriting some code from PHP to Go, I remember that simply thinking about "what to do with err" led me to realize we had a ticking time bomb - one that could explode in production. We had never realized that a certain line of PHP code could potentially throw an exception, and letting it bubble up the stack would have resulted in data corruption. With Go's explicit error handling, this issue became immediately obvious.
Generally you want to do several classes of things with exceptions in web apps:
1. Return a 500, possibly rendering a nice error page.
2. Log why it occurred.
3. Roll back changes you were making at the time in the database.
And you might also want to do other things, like propagate the error via tracing, increment monitored metrics and many other things. All these are easily done with exceptions, and will often be done by frameworks for you. In desktop apps you may also want to trigger a crash reporter, display a sorry message to the user, and if the exception was inside something like a button click handler you may even be able to proceed safely too.
Given the level of bugginess in untested error handling codepaths that crop up in languages without them, exceptions are definitely the way to go.
Also, ignoring an error condition (by either forgetting about it, or simply doing the nice and tidy if err dance with no real error handling in place, just a log or whatever) is much worse and can lead to silent data corruption.
All you can do is what you've described - catch all exceptions at the top level and log them. It's a valid strategy so long as you don't mind your service going down at 3am because someone didn't realize that the call to Foo() on line 5593 could in fact throw exception Bar.
Explicit error handling would make it obvious that Foo() can error, allowing the programmer to do whatever's appropriate, say implement a retry loop. Said programmer would then be sound asleep at 3am instead of playing whack-the-exception.
Case in point is accessing a remote REST endpoint where I might be throttled or the service might be down. I can do something (retry) so I'll write code that probably looks similar to Go with Err:
var retries = 0;
do {
try {
result = await makeServiceCall();
} catch {
if (retries == 3) throw;
retries++;
await Task.Delay(retries * 1000);
}
} while (retries < 3)
The exception bubbling mechanism just makes it optional so you determine when you want to stop the bubbling.If you are using Go, you have no idea what the error you're going to receive is, because the code you call could be calling other code that you have no idea about. You might use existing code that gets modified to call into another module and then you're going to get a whole set of errors that you aren't expecting and won't be able to react to.
What this means is that you have NO way to handle errors except to just error out and bubble up. Because all you can do is look at the error, the best you can do is throw your hands up and say "okay just returning this error." How is this any better than an exception?
throw NoopException()
You tell me what that did.
> or the kludges you need to write to do basic collection transformation pipelines (compared to Java/Streams, C#/LINQ, C++/std etc).
Why hasn't anyone written a good open source for this problem, now that Go has generics? > anything beyond trivial using Go generics
This is the first complaint that I have heard about Go generics on this board. I believe you. Can you share a specific example? It might spur some interesting discussion.