Exiting gracefully instead of panic!

Hi, I just hacked myself a replacement for Option::expect() because I want my command line programm to exit with an error code instead of cryptically panicking.

Is there something in the stdlib or a crate that does that for me?

My trait:

use std::process;

pub trait Graceful<T>{
    fn graceful(self, message:&str) -> T;

impl<T> Graceful<T> for Option<T> {
    fn graceful(self, message:&str) -> T{
        match self{
            Some(val) => val,
            None => {
                println!("Error: {}", message);

What you have is a convenient unwrap_or_else, I'm not aware of a crate for that, but adding a dependency dosen't seem worthwhile if that's all you need.

Thanks, unwrap_or_else is unfortunately not as convenient as you say, because I would have to write:

do_stuff().unwrap_or_else(|| {
    println!("Error: something went wrong");

all over the place, and that's a bit verbose.

Write an extension trait for Option and Result that provides an expect_or_exit method.

1 Like

As many similar error handling concerns, I believe this should be bubbled all the way to the top and handled there.

Following this line of development leads to code that can die at any time and especially not clean up properly.


Of course this is bad design in most cases, especially libraries and so on.
In my case however I deal with a commandline tool and the errors on which I use this are basically unrecoverable.

Even then, you could create a fn my_main() -> Result<(), String> and try! all your expressions that can fail (and add expect where appropriate to create nicer messages).

Then you can simply match on the result of my_main in the real main and print a nice error.

In that case, or_else is the appropriate API ( Option in std::option - Rust ).

1 Like

On second thought, you're right.
I'm bubbling it all up now

Right. I meant that. Expect would just keep on panicking