পাঠ ১২.৬

Error-গুলোকে standard error-এ পাঠানো

Writing Error Messages to Standard Error Instead of Standard Output

এতদূর সব output আমরা println! দিয়ে print করছি — যেটা standard output (stdout)-এ যায়। কিন্তু terminal-এ আরেকটা stream আছে — standard error (stderr)। Error message stderr-এ পাঠানো প্রথা।

stdout বনাম stderr

  • stdout — actual program output (search result, যেমন)।
  • stderr — error message, diagnostic।

এই separation-এর সুবিধা — user shell-এ > দিয়ে stdout file-এ redirect করতে পারে; error তখনো terminal-এ visible থাকবে।

এখনকার সমস্যা

terminalbash
$ cargo run > output.txt

কোনো argument দিইনি — error হচ্ছে। কিন্তু error message println!-এ আছে, তাই সেটাও output.txt-এ redirect হয়ে গেছে। File-এ এখন:

output.txttext
Problem parsing arguments: not enough arguments

User error দেখতে পেল না, file-এ ভুল content। ভুল behavior।

eprintln! macro

Standard library-এ eprintln! macro আছে — println!-এর মতোই, কিন্তু stderr-এ লেখে। Error case-গুলোতে replace:

src/main.rsrust
use std::env;
use std::process;

use minigrep::Config;

fn main() {
    let args: Vec<String> = env::args().collect();

    let config = Config::build(&args).unwrap_or_else(|err| {
        eprintln!("Problem parsing arguments: {err}");
        process::exit(1);
    });

    if let Err(e) = minigrep::run(config) {
        eprintln!("Application error: {e}");
        process::exit(1);
    }
}

লক্ষ্য — শুধু error message-এ eprintln!; আসল search result run-এর ভিতরে println!-এই থাকছে।

এখন behavior

Argument ছাড়া (error case):

$ cargo run > output.txt
Problem parsing arguments: not enough arguments

Error terminal-এ visible, output.txt empty। ✓

Valid argument-এ:

$ cargo run -- to poem.txt > output.txt
output.txttext
Are you nobody, too?
How dreary to be somebody!

Terminal-এ কিছু না, file-এ শুধু actual result। ✓

minigrep complete!

৬টা পাঠে আমরা যা শিখলাম:

  • Command line argument-এর iterator।
  • File system module-এর read API।
  • Modular design — Config struct, run function।
  • Error propagation — Result, ?, Box<dyn Error>।
  • Library/binary split।
  • Test driven development — failing test থেকে শুরু।
  • Lifetime in real-world function signature।
  • Environment variable reading।
  • stdout বনাম stderr।

ছোট হলেও — এই project-এ Rust-এর প্রায় সব core feature use হয়েছে।

এই পাঠ থেকে যা শিখলে

  • stdout = actual output, stderr = error/diagnostic।
  • > redirect শুধু stdout-এ।
  • eprintln! stderr-এ — error log-এর জন্য convention।