Skip to content

Commit 92bb2fa

Browse files
committed
Make error messages user friendly
1 parent 9072fed commit 92bb2fa

3 files changed

Lines changed: 47 additions & 32 deletions

File tree

Cargo.lock

Lines changed: 32 additions & 18 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,4 @@ name = "mdtable"
1717
[dependencies]
1818
clap = "2.33.0"
1919
pad = "0.1.5"
20-
21-
[profile.release]
22-
opt-level = 3
20+
easy-error = "0.1.1"

src/main.rs

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
1+
extern crate easy_error;
12
extern crate clap;
23
extern crate pad;
34

45
mod config;
6+
use config::Config;
57
use pad::PadStr;
6-
use std::io::{self, Result, BufRead, BufReader};
7-
use std::fs::{self, File};
8+
use easy_error::{ ResultExt, termination, ensure };
9+
use std::io::{ self, Result, BufRead, BufReader };
10+
use std::fs::{ self, File };
811
use std::cmp::max;
9-
use config::Config;
1012

1113
fn read_lines(file: &Option<String>) -> Result<Vec<String>> {
1214
match file {
@@ -85,22 +87,23 @@ fn format_pretty(data: &Vec<Vec<String>>) -> String {
8587
].join("\n")
8688
}
8789

88-
fn main() {
90+
fn main() -> termination::Result {
8991
let config = Config::from_args();
90-
let lines = read_lines(&config.file).expect("Error when reading input");
92+
let lines = read_lines(&config.file).context("Error when reading input")?;
9193
let data = parse_table_data(&lines, &config.separator);
9294

93-
if data.len() < 2 || data[0].len() == 0 {
94-
eprintln!("Bad Input: Requires at least 2 rows (including header) and 1 column.");
95-
std::process::exit(1);
96-
}
95+
ensure!(
96+
data.len() > 1 && !data[0].is_empty(),
97+
"Input requires at least 2 rows and 1 column."
98+
);
9799

98100
let table = match config.minimize {
99101
true => format_minimized(&data),
100102
false => format_pretty(&data),
101103
} + "\n";
102104
match config.out {
103-
Some(f) => fs::write(f, &table).expect("Error when writing output to file"),
104-
None => print!("{}", &table),
105+
Some(f) => fs::write(f, table).context("Error when writing output")?,
106+
None => print!("{}", table),
105107
};
108+
Ok(())
106109
}

0 commit comments

Comments
 (0)