Default error handling function?

I know that in Rust I can write main like:

#[tokio::main]
async fn main() -> Result<()> {
//...
}

However, should this function return with an error, it will print it to stdout and exit. I am working on a GUI application and would like to change this behavior so that it displays a message box instead. The only way I know of doing this is using .unwrap_or_else, .or_else, etc., but I don't want to flood my code with a bunch of function calls just to accomplish that. Error propagation exists and I'd like to take full advantage of that if at all possible. So is there a way I can change the default behavior for when returning from main with an std::error::Error result? I know that this can be accomplished in Python, but that's more akin to the panic handler.

The default handler is defined using the unstable trait std::process::Termination, in particular the code handling Result is here.

Using this trait to define your own handler does only work on nightly, requires you to define your own alternative to the Result type, probably also a Try instance for perfect ergonomics, so there’s gonna be a lot of boilerplate. Furthermore it can only be executed after the tokio runtime already finished, so this could introduce extra problems with a GUI.


Thus I’d suggest to handle the Result manually. You can still use propagation when you handle the Result in the main function. Make the main function small and mostly only do the error handling there; if your current main function is super long and contains a lot of logic and you’re concerned about having to duplicate the error handling code otherwise, put all that code into a different, new function not named main.


Edit: Or do you mean you don’t want to exit the program at all but handle the error instead and continue somehow? I don’t see how any kind of panic/error handler in Python could magically help you in that case without any kind of explicit control flow stating how to resume program execution with potentially missing Ok(..)-values, but I also don’t really know Python.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.