105 points · by phonebucket · 5y ago · 111 comments
- Exceptions, so you don't need error handling
- stack traces so you know the entire call tree. This is pretty important -- without stack traces, it is very hard to make sense of error messages like "Cannot open file 'none'" -- the filename is clearly wrong, but where did this come from.
- chained exceptions so you can add context trivially. Doing "try: ... except: raise Exception('Cannot load config')" will print both error messages and two stack traces, so you know both original error and better description.
- verbose by default so if you don't put any effort into error handling, you get lots of details. This is somewhat controversial -- when some people see large stack traces their eyes glaze over and they just stop reading. But as a program's author, I love this -- the stack traces are informative enough I can often figure out what's wrong immediately.
Unchecked exceptions don't tell the caller something might go wrong. Fine for Python, where strong guarantees aren't a thing anyway, but any statically typed language cannot be content with essentially adding bottom to every single type.
Checked exceptions have failed, or at least I haven't seen anybody fix their issues. They proliferate spurious exception types in interfaces. They are inflexible, as they usually can't be generic. They suck at typing error cases for higher order functions. They're big heavy and expensive, so can't be used for hot code paths. They're exceptions but more often than not you want to signal expected failure...
The list goes on...
Failure modes are an abstraction violation; they're a function of implementation. That's what makes checked exceptions not work, at the end of the day. Information-carrying exceptions reveal implementation details. So a module author must decide between hiding details and wrapping everything up in module-specific exceptions that user code can't actually use to make decisions most of the time, or expose implementation details that turn into a versioning problem over time.
There's roughly two situations for error handling: near the leaf of the call tree, where you have enough context to deal with an error, and need to switch on error type and take compensating action; or near the root of the call tree, in the main loop, where you log errors and terminate requests etc. in a generic way (e.g. 500 response).
Exceptions aren't ideal for the first situation but are great for the second. Error codes are adequate for the first situation - monadic error types (Result<T>, Either) are a bit better - but suck horribly for the second, because you need to manually unwind, writing boilerplate that should be automatic.
And at the limit, error types are isomorphic to checked exceptions, with the same problems, and more - error types introduce an aggregation problem, where multiple errors need to be joined together. You can still get that with exceptions too but it usually requires parallelism.
There is actually a third case: in library code which calls other code which may fail. Take java.io.BufferedReader - to be usable, it has to be at a level of abstraction where it cannot deal with any errors the underlying Reader may throw; but the code using BufferedReader will have provided it with its underlying Reader, and will have a good idea of what errors are reasonable to expect from it.
The reason java's checked exceptions are so bad is that they cannot (or could not, before generics, and hence in most of the standard library do not) serve this use case, leading to checked exceptions that one really can't do anything with.
At least in Rust, Result<t> can be unwrapped and bubbled up (in the error case) with a single `?`.
public int java.io.Reader.read() throws IOException
As I see it, the purpose of checked exceptions was to allow declaring expected failure modes in the function signature, so that the programmer (and the compiler!) could check against them - but when my StringReader declares itself capable of throwing an SSLException (subclass of IOException), this benefit is lost. Instead, I must rely on other sources to determine which errors may actually occur, and which I can't do anything about - and the latter I must swallow or pollute all of my package's function signatures with. If the Reader interface had instead been generic java.io.Reader<T extends Throwable>
read() could be declared as public int read() throws T
This would rescue much, and is something that could be done in modern java; but by the time generics were introduced, all the core packages like java.io were written, and the patterns for how to deal with checked exceptions were set.In Java, unchecked exceptions are similar to Rust's panics. Sure your less inclined to catch panics than you might be to catching unchecked exceptions, but you can do it in either. Though perhaps Java's Error is closer to a rust panic.
Checked exceptions are just like the Result type IMO. The discoverability of the error surface is the same, you just don't get the nice pattern matching and sum types to handle/represent it.
What I'm getting at is that I'm a fan of the way Rust does error handling, but I don't get _why_ it feels different to the way Java does it. On the surface they're the same, but I loathe the Java approach. Maybe it's just whatever the opposite of rose-tinted glasses is.
https://devblogs.microsoft.com/oldnewthing/20050114-00/?p=36...
// bad
NotifyIcon CreateNotifyIcon()
{
NotifyIcon icon = new NotifyIcon();
icon.Text = "Blah blah blah";
icon.Visible = true;
icon.Icon = new Icon(GetType(), "cool.ico");
return icon;
}
// not-bad
NotifyIcon CreateNotifyIcon()
{
NotifyIcon icon = new NotifyIcon();
icon.Text = "Blah blah blah";
icon.Icon = new Icon(GetType(), "cool.ico");
icon.Visible = true;
return icon;
}
What is the problem with the first version and how is the second version fixing it?I would add if you want to be correct then the addition signature should be (IntX, IntX) -> Either<IntX,Error>. Are you going to check also the return value of every arithmetic operation?
For me potentials errors are everywhere, so exception aren't bad, even if they make writing 'exception safe' code hard. That's why I was quite interested in the Vale language which claims to improve RAII: https://vale.dev/blog/next-steps-raii
1. Statically typed.
2. Unchecked exceptions by default. IE, implicit bottom on every type.
3. Optional checked exceptions. Implementation could be `checked` keyword (e.g. `checked fun foo() throws XyzError {}`), or a generic type, or something else depending on the language. In order to mark something as checked, it must catch all exceptions from unchecked values it touches.
4. The compiler infers exceptions types when possible. So, if a regular unchecked function (`fun bar() {}`) only calls checked functions (foo from above), the compiler will carry the information about what can be thrown (XyzError) up the chain, even if there is no explicit signature. This way if another function (`checked fun baz() {}`) calls bar(), then it only has to catch or declare the XyzException, rather than all exceptions generically.
Finally, and to tie this all together: as a matter of style, reserve exceptions for actual unexpected errors. To use an example from downthread, a JSON parsing library should not be throwing parsing errors, it should be returning a Maybe<Parsed, Error>. Why? Because the library cannot determine whether the error is unexpected. If you're using it to parse user input, then yes, you're going to frequently encounter invalid data, and this should be part of your normal control flow, not something that can crash your application at runtime (you may want to log the event, maybe with a stack trace, but without interrupting normal operations). On the other hand, say you're parsing JSON from your database, (also, why are storing json in your db? But bear with me..). And invalid json means data corruption, which means your db is fubar. Then, it's fine to throw, because in that case you're operating on state that you assumed to be impossible, and your program behavior is now undefined.
The key point here is that exceptions are useful as a safety valve for early termination in the case of invalid assumptions. That's a subset of all error handling. If you try to force all error handling into the same paradigm and the same level of reliability, you're going to have awkward edge cases.
One question is whether the thing happening is really unexpected to begin with. Why would you throw an exception when you know you're dealing with the file system and a file might not be there?
If you treat all "tainted" contexts are error-prone and implement proper error handling and relevant logging, you might never need to throw an exception because those situations aren't really exceptional to begin with.
Another you might ask yourself is whether your language of choice has stack traces that are easily parsable, because you might not be allowed to expose all app internals in all contexts.
A third is whether it pays to have that high a verbosity in your logs. In other words, do you really need a stack trace? Is it worth the performance overhead? Is it worth the code clutter of having try/catch/finally's everywhere?
A lot of this comes down to preference, but I think there's a valid case to be made for the approach that Exceptions are only for truly exceptional cases. Like nulls, god objects or deep inheritance hierarchies, they are vastly overused in my opinion.
I’ve steadily been concluding that, in a vacuum, result-based errors are vastly superior to exceptions for potentially-recoverable errors, but that you absolutely require static typing before the ergonomics become acceptable.
One important thing to also realise is that result-based errors aren’t actually incompatible with stack traces, chaining or being verbose by default, though Rust chose to eschew those features in its standard library, because it wasn’t clear (and still isn’t) exactly how it’s best to do that, especially if you’re trying to minimise cost, which a language like Rust is. That’s why there are so many experiments, such as anyhow.
Result-based errors is also excellent at some forms of composition that exceptions are completely useless for; for example, in Rust an iterator can yield results, and most file system stuff does that, so you can use things like map, filter, &c. on the iterator—you can even collect `impl Iterator<Item=Result<T, E>>` to `Result<Vec<T>, E>`, easy early return semantics. Anything like this is not at all elegant in Python.
It's because some nested implementation detail API several layers done can take arbitrary streams, and the String based implementation is done by creating a stream for that string, but the stream api allows for IOExceptions in the case of streams from disk or network devices etc.
What reasonable recovery option is there then? You can swallow the exception, because it's impossible for now, but your linter/teammates will complain at you and it could change in future to be possible since it's in the API contract. You could have your application re-raise the exception, propagating the problem further. Neither option is great.
[1]: https://fasterxml.github.io/jackson-databind/javadoc/2.7/com...
try {
....
}
catch (IOException e) { throw new RuntimeException(e); }
It asserts "I believe this error can never happen - so if it does, just re-raise it and it'll get to the top level and the request or program will terminate - which isn't a problem, as, as I've said, this can never happen".As we all know here, sometimes things that can never happen do happen e.g., as you stated, you initially wrote the program knowing it took a stream based on a string, but later that got changed to something that reads from a network. Having that error raised and logged top-level is the ideal outcome if such a mistake is made.
This syntax is verbose and I do wish there were a better syntax (e.g. Lombok @SneakyThrows is a hack which improves the situation somewhat) but the approach is the correct one.
And it also shows that you've thought about the exception. I even often find myself putting a little comment, mainly meant for future developers reading the code to whom it might not be obvious why this could never happen:
// Can never happen: Stream is always a string
catch (IOException e) { throw new RuntimeException(e); }> What reasonable recovery option is there then?
adrianmsmith's answer seems to have it, here are some rather less useful thoughts, for good measure:
The C++-style approach might be to have a boolean template parameter in the Stream API, allowCheckedExceptions, to change the signatures accordingly. As Java lacks specialisation, I don't imagine there's a way to do anything similar, short of having the library offer two very similar Steam APIs, one that permits throwing of checked exceptions and one that doesn't.
edit I suppose the standard library could offer a wrapper around the Stream API, to only accept non-throwing streams, and to return a NonThrowingStream. Internally this wrapper would presumably use the strategy adrianmsmith explained.
This pattern is equivalent to Rust's `unwrap` and `expect`, than can be called to transform a recoverable error into a panic.
There is no distinction drawn between "small error" and "catastrophic failure", anywhere, at anytime, some piece of underlying code may throw nearly nearly any exception up at you by surprise which is a fun adventure in "what will fail next when I shift my attention away slightly". So few libraries properly utilise context: "ValueError on line 1:44" in whatever large file you're reading through (looking at you Pandas), doesn't tell me what the data was, nor what it was expecting, or the real line/position in the file or give you any way of recovering and resuming.
For example:
`Error: CookingError(CakeBaker(TemperatureCOutOfRange(999, 250)))`
This has the added benefit of not forcing your error handling methodology on users of your libraries.
Error handling is hard, Go doesn't hide the complexity, but a lot of other languages try to handwave the complexity away. Either way, programmers are by default lazy, and you end up with "Error 500: connection refused".
You can improve on this a little by using something like https://github.com/pkg/errors, which gives your errors a stack trace by default. But now your errors are hideous and unlikely to be fixable by the average user.
Ultimately the only way to get clean, informative, and debuggable error messages is for the programmer to attend to each and every one. And no one wants to do that, because it's a pain, it slows you down, it gets in the way of solving The Problem At Hand. So unless the language itself somehow forces you to wrap all your errors in nice context strings, it ain't gonna happen.
Except that (no pun) Go has both exceptions in the forms of panics AND its horrible error interface. I don't like exceptions but I'll take exceptions over Go glorified return codes anytime. No amount of "decorating" that system makes it better. There is nothing to it. Rust is a bit better on that matter BECAUSE Rust has the syntactic sugar to make errors as value painless to deal with. Go doesn't.
Sometimes on your server, you have 15 IO operations to perform, you just want to log on failure and return error 500 to the user. This is the case where go doesn't shine at all, what do you do? aside from being tempted to resort to a GOTO statement?
I'd argue that this article is evidence that Rust's syntactic sugar doesn't really help, it just seems like "official" encouragement to do the wrong thing (pass the buck).
I disagree.
try{
dothis();
/* ... 14 lines of dothis(); like */
catch(error){
log(error);
return responseCode(500);
}
sounds easier to both write and maintain to me. Only a handfull of times you'd ever want to deal with each exception separately. And when you do, it's not much more verbose than if err!=nil{ ... }.Let's not forget there are more options than Go's and Rust's approaches. If some languages made error handling hard, it does not mean it is hard in general.
catch (Exception e) {
log.error(e);
}
Which caused the following error output ERROR: could not connect
(mentally adjust to Java syntax, error message, don't remember off the top off my head)I'm not joking. Having overly-verbose errors by default will make people just swallow everything at some point or another.
That particular example was triggered, IIRC, by a configuration file containing a malformed IP address, which was interpreted as a hostname, which resolved into an NXDOMAIN, which caused a magic connect-socket-to-dns-name-or-ip-address call to fail with a generic message when that socket was lazy-connected in an unrelated code path.
If the app is to be used by user unfamiliar with language, and there are no robust error reporting systems -- think website or desktop app -- then this approach actually makes sense. But in the environment where most investigation is done via the logs, and many bugs are not trivially reproducible? Not so much.
use snafu::{Snafu, ResultExt};
#[derive(Debug, Snafu)]
enum Error {
#[snafu(display("Failed to read {}", filename))]
ReadInput { filename: String, source: std::io::Error },
}
type Result<T, E = Error> = std::result::Result<T, E>;
fn main() -> Result<()> {
let filename = "input.txt";
let s = std::fs::read_to_string(filename).context(ReadInput { filename })?;
println!("{}", s);
Ok(())
}
Unfortunately, this uses the default `Debug` formatting, so what is printed to the user in this `main` example is still less-than-ideal: Error: ReadInput { filename: "input.txt", source: Os { code: 2, kind: NotFound, message: "No such file or directory" } }
I encourage using the `Display` formatter or something more complete.I find that doing this rigorously creates what I call a "semantic backtrace", where the linked list of (error, context, underlying cause) provides a great deal of insight into the problem.
The next release of SNAFU will incorporate something that allows for stringly-typed errors:
use snafu::{ResultExt, Whatever};
type Result<T, E = Whatever> = std::result::Result<T, E>;
fn main() -> Result<()> {
let filename = "input.txt";
let s = std::fs::read_to_string(filename)
.with_whatever_context(|_| format!("couldn't read {}", filename))?;
println!("{}", s);
Ok(())
}
You will also be able to combine stringly-typed errors with the structured errors.Other features of the currently-released SNAFU:
- Custom error types
- Backtraces
- Extension traits for Results / Options / Futures / Streams
- Suitable for libraries and applications
- no-std compatibility
- Generic types and lifetimes
[SNAFU]: https://crates.io/crates/snafuIdeally the fact that you use SNAFU should not escape from your library; I encourage creating an [opaque] error in most cases.
The current deliberate "leak" is that we implement a [trait] that exposes the ability to get a backtrace from a SNAFU error because the standard library has not yet stabilized backtraces. Once those are stabilized, we should be able to completely isolate and only operate through the `std::error::Error` trait.
[opaque]: https://docs.rs/snafu/0.6.9/snafu/guide/opaque/index.html
[trait]: https://docs.rs/snafu/0.6.9/snafu/trait.ErrorCompat.html
However, when possible, giving _actionable_ info can really help, especially if the user can see that error.
For example, you can try to explain why this file is expected, and give a link to the spec/doc. Extremely helpful when called at 4am in production.
Alternatively, I've seen some experiments with extreme reproducibility: capture the full context (network requests, filesystem, db state, etc.), and spin up an instance with that state. This way devs can deterministically reproduce the issue, and fix it. But, it supposes that the application is written to support this fairly well (by either being very functional, or by having probes in all non-pure functions).
Troubleshooting hints should live in production runbooks, which tell you, for any firing alert, what is it that might cause it, how to investigate further, where the code lives, etc.
The author gave a great talk about error handling at this year’s rust conf[1].
[0]: https://docs.rs/color-eyre/0.5.4/color_eyre/ [1]: https://m.youtube.com/watch?v=rAF8mLI0naQ
Or, to put it more clearly: there are no errors, only conditions that you dislike. It's better to not burden your programming with your emotional shortcomings, and treat all conditions that you may encounter on an equal footing.
You try to open a file; the file may or may not exist, and both cases are equally likely and you get to decide what your program does in each case. No need to attach an emotionally charged label like "error" in one of the two cases of the conditional. Or worse, as some emotional fanatics do, to bend an otherwise clean programming language by adding features (e.g., exceptions) that help support your sentimental disposition.
Please don't take this as an insult, but I don't care what's Pythonic. I care what the community does, and they default to failing fast (to a fault, in my own opinion).
In my opinion, if you suffer a sufficiently fatal error, you should just crash outright and log the trace + error message. Barring that luxury, you should log the trace + error message, then attempt recovery.
That seems to be what unwrap here would do on its own, so why would that be bad practice (assuming the error was fatal in the first place?). Am I just misunderstanding something fundamental?
a) stack traces generally don't capture parameters
b) stack tracers can be totally desynchronized with intent flow
c) stack traces expose unnecessary internal noise
Compare:
Traceback (most recent call last):
File "/var/prod/deadbeef/models/sql/peers.py", line 1337, in tx
db.execute()
File "/var/prod/deadbeef/models/sql/session.py", line 1337, in session
tx(peers.add(a, b))
File "/var/prod/deadbeef/models/__init__.py", line 1337, in AddBGPPeer
session(peers, AddPeers(a, b))
File "/var/prod/deadbeef/views.py", line 1337, in _view_add_peer
AddBGPPeer(user, other)
File "/var/prod/deadbeef/web.py", line 1337, in handle
_view_add_peer(ctx)
Exception: DB connector returned: unique constraint failed
to: Failed to add peer: models.AddBGPPeer(204480, 204480): insert peer: tx aborted: unique constraint failed
The first requires further logging and code reading to understand what might've caused the error. The latter immediately gives you information you need to understand what happened (the validation layer didn't catch an invalid self-reference, causing a database UNIQUE constraint to fail, and the database code caller didn't gracefully translate this error either).I use the following pattern in Go very often:
foo, err := m.AddBGPPeer(a, b, secret, list)
if err != nil {
pretty := list.StringSeparated(", ")
return nil, fmt.Errorf("AddBGPPeer(%q, %q, _, %s): %w", a, b, pretty, err)
}
The fact that Go error handling is just bog standard Go code allows for some quite complex generation of error messages/hints/contexts that couldn't be caught automatically from a stacktrace, or would have some awkward syntax/semantics with more complex syntactic sugar. Traceback (most recent call last):
File "/var/prod/deadbeef/models/sql/peers.py", line 1337, in tx
db.execute()
File "/var/prod/deadbeef/models/sql/session.py", line 1337, in session
tx(peers.add(a, b))
File "/var/prod/deadbeef/models/__init__.py", line 1337, in AddBGPPeer
session(peers, AddPeers(a, b))
File "/var/prod/deadbeef/views.py", line 1337, in _view_add_peer
AddBGPPeer(user, other)
File "/var/prod/deadbeef/web.py", line 1337, in handle
_view_add_peer(ctx)
Exception: Failed to add peer: models.AddBGPPeer(204480, 204480): insert peer: tx aborted: unique constraint failed Cup
60 skins in DB
104 drivers in DB
thread 'main' panicked at 'Could not find car folder or its skins: acrl_poorsche_911_gt3_cup_2017', src\main.rs:104:17
stack backtrace:
0: 0x7ff72a06deca - std::backtrace_rs::backtrace::dbghelp::trace
at /rustc/7eac88abb2e57e752f3302f02be5f3ce3d7adfb4\/library\std\src\..\..\backtrace\src\backtrace\dbghelp.rs:98
1: 0x7ff72a06deca - std::backtrace_rs::backtrace::trace_unsynchronized
at /rustc/7eac88abb2e57e752f3302f02be5f3ce3d7adfb4\/library\std\src\..\..\backtrace\src\backtrace\mod.rs:66
2: 0x7ff72a06deca - std::sys_common::backtrace::_print_fmt
at /rustc/7eac88abb2e57e752f3302f02be5f3ce3d7adfb4\/library\std\src\sys_common\backtrace.rs:79
3: 0x7ff72a06deca - std::sys_common::backtrace::_print::{{impl}}::fmt
at /rustc/7eac88abb2e57e752f3302f02be5f3ce3d7adfb4\/library\std\src\sys_common\backtrace.rs:58
4: 0x7ff729fb93bb - core::fmt::write
at /rustc/7eac88abb2e57e752f3302f02be5f3ce3d7adfb4\/library\core\src\fmt\mod.rs:1080
5: 0x7ff72a06c9e8 - std::io::Write::write_fmt<std::sys::windows::stdio::Stderr>
at /rustc/7eac88abb2e57e752f3302f02be5f3ce3d7adfb4\/library\std\src\io\mod.rs:1516
6: 0x7ff72a06bd18 - std::sys_common::backtrace::_print
at /rustc/7eac88abb2e57e752f3302f02be5f3ce3d7adfb4\/library\std\src\sys_common\backtrace.rs:61
7: 0x7ff72a06bd18 - std::sys_common::backtrace::print
at /rustc/7eac88abb2e57e752f3302f02be5f3ce3d7adfb4\/library\std\src\sys_common\backtrace.rs:48
8: 0x7ff72a06bd18 - std::panicking::default_hook::{{closure}}
at /rustc/7eac88abb2e57e752f3302f02be5f3ce3d7adfb4\/library\std\src\panicking.rs:206
9: 0x7ff72a06bd18 - std::panicking::default_hook
at /rustc/7eac88abb2e57e752f3302f02be5f3ce3d7adfb4\/library\std\src\panicking.rs:227
10: 0x7ff72a06bd18 - std::panicking::rust_panic_with_hook
at /rustc/7eac88abb2e57e752f3302f02be5f3ce3d7adfb4\/library\std\src\panicking.rs:577
11: 0x7ff72a073ab5 - std::panicking::begin_panic_handler::{{closure}}
at /rustc/7eac88abb2e57e752f3302f02be5f3ce3d7adfb4\/library\std\src\panicking.rs:484
12: 0x7ff72a073a77 - std::sys_common::backtrace::__rust_end_short_backtrace<closure-0,!>
at /rustc/7eac88abb2e57e752f3302f02be5f3ce3d7adfb4\/library\std\src\sys_common\backtrace.rs:153
13: 0x7ff72a073a1f - std::panicking::begin_panic_handler
at /rustc/7eac88abb2e57e752f3302f02be5f3ce3d7adfb4\/library\std\src\panicking.rs:483
14: 0x7ff72a0739e0 - std::panicking::begin_panic_fmt
at /rustc/7eac88abb2e57e752f3302f02be5f3ce3d7adfb4\/library\std\src\panicking.rs:437
15: 0x7ff729f3501e - __ImageBase
16: 0x7ff729f3f9eb - __ImageBase
17: 0x7ff729f51486 - main
18: 0x7ff729f40277 - main
19: 0x7ff72a0885f0 - invoke_main
at d:\agent\_work\63\s\src\vctools\crt\vcstartup\src\startup\exe_common.inl:78
20: 0x7ff72a0885f0 - __scrt_common_main_seh
at d:\agent\_work\63\s\src\vctools\crt\vcstartup\src\startup\exe_common.inl:288
21: 0x7ffeb18b7034 - BaseThreadInitThunk
22: 0x7ffeb1e9cec1 - RtlUserThreadStart
That stack track is completely worthless. It tells you literally nothing. Worse, is that while the actual problem is printed, it gets lost with the mess of noise after it. Whereas an error output like this is clearer: Cup
60 skins in DB
104 drivers in DB
Error: Failed to verify series data
Caused by: Could not find car folder or its skins: acrl_poorsche_911_gt3_cup_2017
The core error is that a car or skin folder was missing, and that error caused verification to fail. That's what should be printed, because that's what is relevant.I see the validity of what you're saying, but only in the context of insufficiently verbose third-party error messages. There's no reason that the exception message could not have been more detailed.
In my own projects, I like to design the functions that constitute the "plumbing" in such a way that they rethrow errors with more descriptive errors. We're venturing out into the realm of practice from that of theory, so this is just me sharing for the hell of it, but here's how that looks:
// Helper function meant to be reused in many function definitions
function throwIfFunctionParameterUndefined(functionName, parameterName, value){
if (value === undefined)
throw new TypeError(`${functionName} invoked with undefined parameter ${parameterName}`)
}
function doThing(paramA, paramB, optionalParam){
// Assert and throw for things we can guarantee in a meaningful way
// Since this is plumbing, we trust that higher level functions will catch if this is recoverable
const throwIfParameterUndefined = (paramName, value) => throwIfFunctionParameterUndefined('doThing', paramName, value)
throwIfParameterUndefined('paramA', paramA)
throwIfParameterUndefined('paramB', paramB)
// Rethrow errors from third party libraries
try {
thirdPartyThing()
} catch (err){
err.message = 'thirdPartyThing invoked by doThing failed with message:\n' + err.message
throw err
}
}Sorry, I might've made that up :).
What I meant is that stracktraces do not necessarily reflect the actual code path that the error was caused by (eg. with deferals to internal work queues), and even if they do, they tend to have terrible SNR (too much technicalities of how your code is structured, not enough information about the data that caused the error in the first place).
Outside of unwrap, which actually crashes out, is it not possible to access the stack trace? Forgive my ignorance, I've never worked in Rust nor any other on-the-metal languages before!
So if you want your "exception" to be able to be handled by the caller, you have to indicate it otherwise, usually with enums.
The first kind of error is the "programming oops" error--division by 0, null pointer dereference are obvious examples. These kinds of errors potentially arise from almost everywhere, but you're never expecting to handle them except at the very highest catch-all level. Consequently, you generally want to have maximum-detail error logging of the entire stack trace and perhaps the environment around the cause of the failed exception to understand what wrong.
The second case of error is the expected error class--I/O exceptions and file-not-found are the prototypical examples here. Generally, this will be handled immediately, and you may be unwilling to pay the high performance penalty of constructing the exception context if you are going to throw that context away on the very next line. Instead, your want your exception context to be no more expensive than an error code.
The third and final class of error is application errors that combine both properties. You want contextual information for errors, explaining not just what went wrong but also the sequence of processing decisions that led you to do that wrong step (e.g., pointing to configuration file entries). A stack trace isn't necessarily the worst default for context, but it's usually far from the best information. The application, when handling the error, may well want to poke heavily at the error details to display it in more user-friendly ways.
As it exists at present, most error handling systems focus on either the first or second class of errors. More rarely, they try to handle both of these classes (Rust's Result/panic divide is an example here). But there is very little support for the third class, with the closest alternative being providing context via chaining of exceptions.
The zen of erlang (https://ferd.ca/the-zen-of-erlang.html) goes more in depth if you're curious.
Rust used to be much more Erlang-like in this regard back in the days when it had such a runtime, but when the runtime was removed, so was the ability to work like this.
use std::fs;
fn main() -> Result<(), String> {
let s = "a.rs";
match fs::read_to_string(s) {
Ok(v) => print!("{}", v),
Err(v) => Err(format!("{} {}", s, v))?
}
Ok(())
}
or you can use `map_err`: let out_s = fs::read_to_string(in_s).map_err(|e|
format!("{} {}", in_s, e)
)?;I'd like to see error handling supported in a transactional way, which at least would roll things back to a clean state before the error happened. Of course if you performed an operation which cannot be rolled back, then so much for my great idea.
Failures happen, and robust software should deal with them in a predictable manner. Not all software needs to be able to recover from failures automatically, but they should remain in a consistent state so that an operator can fix the situation, allowing the system to recover. A database system unexpectedly going down is a failure, and a system that expects it will never happen can't be considered correct.
Errors are the result of a mistake: Either there's an invalid input from the user, or a bug has caused data corruption. Errors can be detected with defensive coding (eg. by validating input), but often systems can't recover from errors, so they to be communicated to the user. You'll want systems to abort their current task if they encounter errors, as the state will be undefined, and continuing may make the situation worse.
Exceptions are great when you are prototyping something. You will not have to bother about the very very very edge case. This is important when you have HOFs.
For robust production software though, you need something like result type or checked exceptions.
Rust's panic is better since it makes it clear that you are just completely giving up and that the scenario is not being handled.