Exiting gracefully instead of panic!


#1

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);
                process::exit(1);
            }
        }
    }
}

#2

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.


#3

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");
    process::exit(1)
});

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


#4

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


#5

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.


#6

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.


#7

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.


#8

In that case, or_else is the appropriate API ( https://doc.rust-lang.org/std/option/enum.Option.html#method.ok_or ).


#9

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


#10

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