From 9d2a896f0180e82d3728c5961c1312502100e69c Mon Sep 17 00:00:00 2001 From: WriterV2 Date: Sat, 3 Sep 2022 20:01:18 +0200 Subject: Add anyhow error handling --- src/main.rs | 38 ++++++++++---------------------------- src/works/mod.rs | 12 +++++------- 2 files changed, 15 insertions(+), 35 deletions(-) (limited to 'src') diff --git a/src/main.rs b/src/main.rs index 7f658ef..4af487e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,42 +1,24 @@ +use anyhow::Result; use tera::{Context, Tera}; use crate::works::Works; mod works; -fn main() { - let tera = match Tera::new("templates/**/*.html") { - Ok(t) => t, - Err(e) => { - println!("Parsing error(s): {}", e); - ::std::process::exit(1); - } - }; +fn main() -> Result<()> { + let tera = Tera::new("templates/**/*.html")?; let context = Context::new(); - let output = tera - .render("index.html", &context) - .expect("Failed to render index.html"); + let output = tera.render("index.html", &context)?; - std::fs::write("docs/index.html", output) - .expect("Failed to write rendered output to index.html"); - - let file = match std::fs::File::open(std::path::PathBuf::from("stories.json")) { - Ok(file) => file, - Err(err) => panic!("Trying to open stories.json in readmode - {:?}", err), - }; + std::fs::write("docs/index.html", output)?; + let file = std::fs::File::open(std::path::PathBuf::from("stories.json"))?; let stories = works::stories::Stories::new_from_file(file); - println!("Stories: {:?}\n", stories); - - let context = stories.create_tera_context(); - println!("Context: {:?}\n", context); - - let stories_html_output = tera - .render("stories.html", &context) - .expect("Failed to render stories.html"); + let context = stories?.create_tera_context(); - std::fs::write("docs/stories.html", stories_html_output) - .expect("Failed to write rendered output to stories.html"); + let stories_html_output = tera.render("stories.html", &context?)?; + std::fs::write("docs/stories.html", stories_html_output)?; + Ok(()) } diff --git a/src/works/mod.rs b/src/works/mod.rs index f062565..cfd302d 100644 --- a/src/works/mod.rs +++ b/src/works/mod.rs @@ -1,18 +1,16 @@ +use anyhow::Result; use serde::{Deserialize, Serialize}; pub mod stories; pub trait Works: for<'a> Deserialize<'a> + Serialize { - fn new_from_file(file: std::fs::File) -> Self { - match serde_json::from_reader(std::io::BufReader::new(file)) { - Ok(work) => work, - Err(err) => panic!("Trying to create work from JSON File - {:?}", err), - } + fn new_from_file(file: std::fs::File) -> Result { + Ok(serde_json::from_reader(std::io::BufReader::new(file))?) } - fn create_tera_context(&self) -> tera::Context { + fn create_tera_context(&self) -> Result { let mut context = tera::Context::new(); context.insert("works", &self); - context + Ok(context) } } -- cgit v1.2.3