Using panic!
To understand error handling in Rust, we need to begin with the panic!
macro. We can use the panic!
macro when the application encounters an unrecoverable error and there's no purpose in continuing the application. If the application encounters panic!
, the application will emit the backtrace and terminate.
Let's try using panic!
on the program that we created in the previous chapter. Suppose we want the application to read a secret file before we initialize Rocket. If the application cannot find this secret file, it will not continue.
Let's get started:
- Add the following line in
src/main.rs
:use std::env;
- In the same file in the
rocket()
function, prepend the following lines:let secret_file_path = env::current_dir().unwrap().join("secret_file"); if !secret_file_path.exists() { panic!("secret does not exists"); }
- Afterward, try executing
cargo run
without creating an empty file namedsecret_file...