Working with mistakes

How would rustoceans handle Options and a Result in the code below? In other words, would it use ? or would it use match to handle possible errors? What would a software manager in a software industry who likes to use rust as a language do?

    let taskstatus = TaskStatus::from_string(value);

    let substitute = state
        .insert(
            key.clone(),
            serde_json::from_str(taskstatus.to_string().as_str()).unwrap(),
        )
        .unwrap()
        .as_str()
        .unwrap()
        .to_string();

    state::escrever_arquivo("src\\arquivo\\state.json", state).unwrap();
    println!(
        "O status {} foi alterado com sucesso para {}",
        substitute, value
    )

I highly recommend reading Andrew Gallant's posts on error handling in Rust:

(Also please post code as a code snippet and not as a screenshot. Screenshots are hard to read, can't be copied as text and can't be interpreted by screen readers.)

9 Likes

Thank you very much

Might I ask how you discovered these blog posts? I was not even aware of the authors name, and I did an extended Google search before I started creating the chapters about option and result types some months ago. Actually, I typically have problems finding good blog posts (again). I think I saw a not too bad post maybe six months ago, I was going to read it some day, but I can not remember the title or topic.

I also find it difficult to find good blog articles

I discover most of the good Rust materials here on URLO, actually. Same in this case, where burntsushi linked them in a discussion I was participating in about interfaces that panic.

FWIW, here a list of blogs (besides the official blogs from rust-lang.org and the foundation) I follow for Rust-related stuff:

16 Likes

THanks, that is a detailed list, and I think I am still unaware of most of them.

What I have bookmarked myself is

and the condensed book The Rust Book (Abridged) | The rs Book

3 Likes

You've probably heard of some of their crates. They are also on a team and have been on others.

Other blogs that come to mind... that weren't just mentioned above...

9 Likes

A couple more:
https://github.com/pretzelhammer/rust-blog
https://dystroy.org/blog/

7 Likes

Hands down the best resource about the more technical/stranger parts of borrow checking and the type system. Probably what I link here the most, besides the Reference, Cargo book and the one blog post that somehow magically solves all problems people have with tokio.

4 Likes

Well, as a part owner of a software company, all be it very small, I have a particular philosophy on the issue of errors, options and such.

To my mind the first thing to do is to stop thinking of errors as some special, typically unpleasant and annoying, thing that you don't really want to think about. That you want to get out of the way of your programs "happy path" that is so clean and pure and desirable.

Instead think of errors as just another thing that your program can do. Just another state it can get into. Clear your mind of any difference between that nice clean concept of your algorithm or code execution path and some other path that you now think of as "error".

Why? Because errors happen. They are a normal part of the life of your code. As surely as death and taxes are for us. You have to deal with them as surely as any other step in your program. You have to cater for "errors" somehow just like any other decisions made in your program.

What this means is that how you respond to what you think is an error situation entirely depends on what you want or need to do when it happens. Maybe not being able to open a file is fatal and the program cannot continue, for example when a config is missing. Or perhaps the user just mistyped a file name and you have to notify the user of that and see what they want to do next.

What I'm getting at is that often we see that people design some code for the functionality they want but they forget to anticipate and design for all the ways it might not go as they expect. The they have a quandary, how do I handle that?

As an example I spend a couple of months building some code that relied on communicating with another device. My plan was that if the communication failed for any reason it may as well just quit with an error message as soon as possible. It's OK, I thought, systemd will start it up again. Turned out though that what I really needed to do was a whole bunch of other things to shut down nicely else the whole system collapsed. At that point it's not a question of should I use unwrap or match or ?, no it's major overhaul of how the whole thing worked.

Sorry, I'm rambling a bit....

But to close, this is why I don't much like the idea of exceptions and to some extent ?. Maybe there is 10 ways my function might not do what I expect. Likely most of them are not really "exceptional". Worse cleaning up my "happy path" by simply throwing an exception or using ? just means I have hyper spaced my problems to some other unknown part of the code with the hope they will deal with it.

5 Likes

Not read a single line of code. Raise an issue (in infrequent event of running the software) if it panics.


https://this-week-in-rust.org/ after you have learnt the language from usual sources.

1 Like

It makes sense what you said, thanks for sharing it with us.

thank you

It's a few years old now, but I have an OPML document on Read Rust with a bunch of blogs that posted about Rust back in the day. May or may not be useful:

2 Likes

Even better than handling Options and Results is to avoid creating them. Looking at your code, my first question would be to ask why you store serde::Value in the HashMap? The use of the HashMap that we can see here requires the HashMap to return a String.

Changing the code to use a HashMap<String, String> will remove most of the unwraps.

3 Likes

Thank you very much

I was trying to explore how the serde_json crate works

tl;dr: Use '?' to early abort and pass the error to the caller, or handle it on the spot, if it makes sense. (For the caller: further pass it up or handle it.)

Option ans Result are concepts from functional programming, called Monads. While the theory is quite complex to understand, the practical application has a good metaphor, well explained by Scott Wlaschin: https://youtu.be/ucnWLfBA1dc?si=TSqs1ZorW-vEY9g6&t=1920