5 ms·
Rust errors without dependencies
- j1elo 10mo agoThat's quite a good amount of boilerplate to create a custom, project-specific handling of errors, which itself can have bugs. During reading I thought "anyhow, at this point you are half way to reinvent the wheel and write your own "anyhow'". I agree with avoiding an explosion of dependencies; but not at any cost. In any case if custom error handling works, then why not. It's just that it feels like a deviation to do extra work on designing and implementing an ideal error handling system with all the cool features, instead of spending that same time working on the actual target of the project itself.
- PhilipRoman 10mo agoAny medium or large C project has these kinds of project-specific (or sometimes company-specific) collections of log macros, error handling macros, etc. The amount of boilerplate here is minimal compared to that.
- vsgherzi 10mo agoIt is, this is the most verbose way of doing it, it can easily be made smaller. The main reason is rust exposes this where other languages tend to hide it so programmers aren’t used to having so much code on error cases. Just my opinion of course
- zahlman 10mo ago> In the recent Cloudlfare outage Cloudlflare's proxy service went down directly due to an unwrap when reading a config file. Me and many other developers jumped the shark, calling out Cloudflare on their best practices. In Cloudflare's defense they treated this file as trusted input and never expected it to be malformed. Due to circumstances the file became invalid causing the programs assumption's to break. "Trusted" is a different category from "valid" for a reason. Especially if you're working in a compiled language on something as important as that, anything that isn't either part of the code itself or in a format where literally every byte sequence is acceptable, should be treated as potentially malformed. There is nothing compiling the config file. > Why is this better than NodeJS ... That feels like it really came out of nowhere, and after seeing so much code to implement what other languages have as a first-class feature (albeit with trade-offs that Rust clearly wanted to avoid), it comes across almost as a coping mechanism.
- kaoD 10mo agoAnd it was treated as potentially malformed and hence the panic. That's what panic is for! When invariants are not upheld at runtime, in Cloudflare's case an abnormal amount of entries IIRC. I mean, if the error was handled what would you have done if not crashing the service with an error message? I think the post's point is that you don't panic if someone submits a malformed PDF (you just reject their request) but I don't think there's any way to gracefully handle a malformed config file that is core to the service.
- 01HNNWZ0MV43FF 10mo agoContinue with the previous config. If the config-loading function was fallible, and that bubbled up somewhere, someone might say, "Oh this can fail, we should do blue-green for configs the same as we do for exes." With it being infallible and a panic, that gets hidden. If I was designing a language to surpass Rust, I'd make panics opt-in. I think Rust has a team looking into no-panic but it's a funny loophole for a language that wanted to eliminate crashes.
- dwattttt 10mo agoI think "eliminate crashes" isn't the way to describe what Rust aims for. Eliminate memory corruption, yes. But one mechanism for achieving that was safely crashing.
- TZubiri 10mo ago>That feels like it really came out of nowhere, and after seeing so much code to implement what other languages have as a first-class feature (albeit with trade-offs that Rust clearly wanted to avoid), it comes across almost as a coping mechanism. It's really not fair to compare these when most of the errors of one language are caught at compile time by the other. It reminds me of that scene from silicon valley "Anything related to errors sounds like your area https://youtu.be/oyVksFviJVE?si=NVq9xjd1uCnhZkPz&t=55 https://youtu.be/oyVksFviJVE?si=NVq9xjd1uCnhZkPz&t=55 Can we not just agree that interpreted languages (save the Ackshually) like python and node need a more elaborate error handling system because they have more errors than compiled languages? It's not a holy war thing, I'm not on either side, in fact I use interpreted languages more than compiled languages, but it's just one of the very well-known trade-offs. In the alternative, you would at least admit that error handling in an interpreted language is completely different than error handling in a compiled language.
- drnick1 10mo ago> I want less code. I want to limit the amount of 3rd party code I pull in. This is mostly due to supply chain disasters over on NPM scaring me and the amount of code dependencies bringing in see rust dependencies scare me. And this is basically why I like the C/C++ model of not having a centralized repo better. If I need some external piece of software, I simply download the headers and/or sources directly and place them in my project and never touch these dependencies again. Unless somehow these are compromised at the time of download, I will never have to worry about them again. Also these days I am increasingly relying on LLMs to simply generate what I need from scratch and rely less and less on external code.
- dkdcio 10mo agoyou could just do that with Rust, right? you’re just saying cargo makes it too easy not to I’m very tempted to go this direction myself with Rust, vendoring in and “maintaining” (using Claude Code to maintain) dependencies. or writing subsets of the crates I need myself and using those. the sprawl with Rust dependencies is concerning
- drnick1 10mo agoYes of course you could do this in Rust. It's just that every resource out there promotes the usage of Cargo, and sells this as an "improvement" over the old school way of managing dependencies manually.
- FridgeSeal 10mo agoCargo will let you vendor code into your repo easily. I think you’re conflating the tool, with how people manage deps. https://doc.rust-lang.org/cargo/commands/cargo-vendor.html https://doc.rust-lang.org/cargo/commands/cargo-vendor.html
- rcxdude 10mo agoit's mainly an improvement because the rust ecosystem has a standardized way to build and distribute packages, so you can reliably add a dependency without build system pain. If you don't think having a reference to a central repo is a good way to go, you can vendor or even just pin your dependencies.
- IshKebab 10mo agoI still think it's kind of mad that the standard library doesn't have better options built in. We've had long enough to explore the approaches. It's time to design something that can go into std and be used by everybody. As it is any moderately large Rust project ends up including several different error handling crates.
- burntsushi 10mo agoI'm on libs-api and I'd personally be on board with something like `thiserror` coming into `std`. But it would need a champion I think.
- epage 10mo agoI think we should provide the building blocks (display, etc like derive_more) rather than a specialized version one for errors (thiserror). I also feel thiserror encourages a public error enum which to me is an anti-pattern as they are usually tied to your implementation and hard to add context, especially if you have a variants for other error types.
- burntsushi 10mo agoYeah I used the weasel-y "something like" for exactly these reasons. :-)
- the8472 10mo agoI don't quite understand the issue about public error enums? Distinguishing variants is very useful if some causes are recoverable or - when writing webservers - could be translated into different status codes. Often both are useful, something representing internal details for logging and a public interface.
- IshKebab 10mo agoI agree. Is he really trying to say that e.g. errors for `std::fs::read()` should not distinguish between "file not found" and "permission denied"? It's quite common to want to react to those programmatically. IMO Rust should provide something like thiserror for libraries, and also something like anyhow for applications. Maybe we can't design a perfect error library yet, but we can do waaay better than nothing. Something that covers 99% of uses would still be very useful, and there's plenty of precedent for that in the standard library.
- athrowaway3z 10mo agoMy controversial take on Rust errors is to use anyhow everywhere until you have an immediate demand for explicit Enums. YANGNI The pros for using anyhow are big: Easily stack errors together - eg file.open().context(path) -, errors are easily kept up to date, and easy to find where they occur. An enum error is pleasing when you're finished, but cumbersome in practice. It's niche situation that you need to write a function that exposes a meaningful Error state the caller can branch on. If the return state is meaningful, you usually don't put it in the Err part. eg parsers using { Ok,Incomplete,Error }. IMO Error enums are best for encoding known external behavior like IO errors. For example: The Sender.send_deadline returning { Timeout, Closed } is the exception in being useful. Most errors are like a Base64 error enums. Branching on the detail is useless for 99.99% of callers. i.e. If your crate is meant for >1000 users, build the full enum. For any other stuff, use anyhow.
- zaphar 10mo agoIf your error domain has only one useful category why not just create an error type with a useful message and be done with it. Why use anyhow at all? You are essentially saying the error domain is small so the work is tiny anyway. anyhow seems useful in the very top layers where you basically just want bubble the useful errors modeled elsewhere to a top layer that can appropriately handle them. I don't think a crate should abdicate from modeling the error domain any more than they should abdicate from modeling the other types.
- athrowaway3z 10mo agoI'm trying to describe a rather large spectrum of situations, and how most of them are favorable (or not unfavorable) to anyhow. I'm not saying the error domain is small per se. Instead, one argument I'm making: what you're describing about errors bubbling up to the top layer, is what happens with the overwhelming majority of errors in my experience. Whether the error space is large or small, just wait until you have an immediate need to treat one error different from the rest. It happens, it's just not common. I didn't steelman the case for when to use enums, but in short: In a tiny error space or as valuable documentation. (The doc value is undermined somewhat when projects use 1-big-error and functions that eg only returns 3 of the 6 possible errors) I'm not advocating removing an Error enum. Just that writing one can and should be postponed, saving a lot of maintenance edits.
- osiris88 10mo agoOP is spot on, no deps is the way. I've been using rust for 8+ years, I remember the experiments around `failure` crate, a precursor to anyhow if I remember right... and then eyre, and then thiserror... It just felt like too much churn and each one offered barely any distinction to the previous. Additionally, the `std::error::Error` trait was very poorly designed when it was initially created. It was `std` only and linked to a concept of backtraces, which made it a non-starter for embedded. It just seemed to me that it was a bad idea ever to use it in a library and that it would harm embedded users. And the upside for non-embedded users was minimal. Indeed most of it's interface since then has been deprecated and removed, and it to this day has no built-in idea of "error accumulation". I really can't understand this. That's one of the main things that I would have wanted an generic error interface to solve in order to be actually useful. It was also extremely painful 5 years ago when cargo didn't properly do feature unification separately for build dependencies vs. target dependencies. This meant that if you used anything in your build.rs that depended on `failure` with default features, and turned on `std` feature, then you cannot use `failure` anywhere in your actual target or you will get `std` feature and then your build will break. So I rapidly learned that these kinds of crates can cause much bigger problems than they actually solve. I think the whole "rust error handling research" area has frankly been an enormous disappointment. Nowadays I try to avoid all of these libraries (failure, anyhow, thiserror, etc.) because they all get abandoned sooner or later, and they brought very little to the table other than being declared "idiomatic" by the illuminati. Why waste my time rewriting it in a year or two for the new cool flavor of suck. Usually what I actually do in rust for errors now is, the error is an enum, and I use `displaydoc` to make it implement `Display`, because that is actually very simple and well-scoped, and doesn’t involve std dependencies. I don't bother with implementing `std::error::Error`, because it's pointless. Display is the only thing errors need to implement, for me. If I'm writing an application and I come to a point where I need to "box" or "type erase" the error, then it becomes `String` or perhaps `Box<str>` if I care about a few bytes. It may feel crude, but it is simple and it works. That doesn't let you downcast errors later, but the situations where you actually have to do that are very rare and I'm willing to do something ad hoc in those cases. You can also often refactor so that you don't actually have to do that. I'm kind of in the downcasting-is-a-code-smell camp anyways. I'm a little bit excited about `rootcause` because it seems better thought out than it's progenitors. But I have yet to try to make systematic use of it in a bigger project.
- llmslave2 10mo ago[flagged]
- speedgoose 10mo ago_, err := fmt.Println("of course golang has some good parts.") if err != nil { return err }
- vsgherzi 10mo agoThe entire blog shows that you don’t need that… sushi showed the same thing in 1.0 Go dosent deviate from the norm. It’s the same style we’ve had back from the billion dollar mistake. Not saying it’s wrong rust’s is just different. Tradeoffs and such.
- morning-coffee 10mo ago> I want less code. I want to limit the amount of 3rd party code I pull in. This is mostly due to supply chain disasters over on NPM scaring me and the amount of code dependencies bringing in see rust dependencies scare me. `anyhow` has exactly one optional dependency (backtrace). `thiserror` has three (proc-macro2, quote, syn) which are at the base of practically the entire Rust ecosystem. Unless the author has zero dependencies in general, I'll bet they have all of the above dependencies already. ¯\_(°ペ)_/¯
- khuey 10mo agoFrom a supply chain security perspective it's worth noting that a version of backtrace already ships in the standard library too.
- vsgherzi 10mo agoAnyhow itself is still a dependency. This is more something I wanted to do and not something I recommend for everyone. Google took a similar approach in how they added rust for chrome. They don’t use an error handling library.
- craftkiller 10mo agonit: `thiserror` has 4 dependencies (proc-macro2, quote, syn, unicode-ident). Indirect dependencies are still dependencies.
- TZubiri 10mo ago>Rust error handling is a complex topic mostly due to the composability it gives you and no "blessed way" to accomplish this from the community. I find it hard to believe. Since a huge class of errors are caught by compile time static analysis, you don't really need an exception system, and errors are basically just return values that you check. It's much more productive just to use return values and check them, wrap return values in an optional, do whatever. Just move on, do not recreate the features of your previous language on a new language.
- hullopa 10mo ago[dead]
- cloudhead 10mo agoThe fact that you either need a third party dependency or a large amount of boilerplate just to get decent error reporting, points to an issue in the language or std library design. I've started also dropping `thiserror` when building libraries, as I don't want upstream users of my libraries to incur this additional dependency, but it's a pain.
- brabel 10mo agoWhy are people disagreeing with this? This is absolutely a problem that most other languages don't have. If you want to claim that Rust's error system is "better" than anything else (as the author did), you should have a good argument about why this exact problem the parent commenter described, which to me is a major problem, does not (maybe) cancel out all the other purported benefits of Rust's error system!
- duped 10mo agoThis isn't a problem in other languages because most other languages don't have strong, statically typed errors that need to compose across libraries. And those that do have the same problem. The general argument against adding something to `std` is that once the API is stabilized, it's stabilized forever (or at least for an edition, but practically I don't think many APIs have been changed or broken across editions in std). The aversion to dependencies is just something you have to get over in Rust imo. std is purposefully kept small and that's a good thing (although it's still bigger and better than C++, which is the chief language to compare against).
- 01HNNWZ0MV43FF 10mo ago> points to an issue in the language or std library design. Rust has a too-small stdlib because they want to avoid a calcified stdlib like C++ and Python, which both have too-big stdlibs. This is a law of nature, your stdlib can either be too small or too big. It cannot be the right size. At least it isn't C.
- cloudhead 10mo ago
- nateb2022 10mo ago> I own the code that I bring into my repo, I belive the standard library is sufficent for my needs without having to pull in more crates. Unless you're working on something with extremely limited scope, dependencies will become unavoidable; without resorting to reinventing many wheels. > This is not THE idiomatic way to write rust but rather the way that I write errors. > impl From<std::num::ParseIntError> for DemoError { > fn from(error: std::num::ParseIntError) -> Self { > DemoError::ParseErr(error) > } > } This introduces a lot of observability risk. You've essentially built a context eraser. By using a generic From impl with the ? operator, you’re prioritizing brevity during the "happy path" write, but you're losing the "Why" of the error. If my_function has five different string-to-int conversions, your logs will just tell you "Invalid Digit." Good luck grep-ing that in a 100k LOC codebase. map_err can help fix this, but look at what that does to your logic: let my_number: i32 = first_input .parse() .map_err(|_| DemoError::new(DemoErrorKind::FirstNumberErr( first_input.into() )) )?; In a real-world refactor, someone is going to change first_input to validated_input and forget to update the variable inside that closure. Now your error message will report the wrong data. It sends the SRE team down a rabbit hole investigating the wrong input while the real bug sits elsewhere. And by calling error.to_string() in your Display impl: DemoErrorKind::ParseErr(error) => write!( f, "error parsing with {}", error.to_string() ), ...you are manually "flattening" the error. You’ve just nuked the original error's type identity. If a caller up the stack wanted to programmatically handle a specific ParseIntError variant, they can't. You've turned a structured error into a "stringly-typed" nightmare. Realistically your risk of mismanaging your boilerplate is significantly higher than a supply chain attack on a crate maintained by the core library team.
- vsgherzi 10mo agoThis particular one is just how I decided to take context. You could easily keep the original error type and add context onto the struct as an additional field. Or an alternative could be to take a string and the error type. The I’m using someone’s library because I don’t trust myself argument doesn’t really track for me.