From 40175f9cdaf6d92facb2f0277661f63460c7f594 Mon Sep 17 00:00:00 2001 From: Ning Sun Date: Sat, 2 Jul 2022 17:54:54 +0800 Subject: [PATCH] test: add example for getting error generated from helper [#512] --- examples/error.rs | 51 ++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 48 insertions(+), 3 deletions(-) diff --git a/examples/error.rs b/examples/error.rs index 3fb874e2b..ca20450d2 100644 --- a/examples/error.rs +++ b/examples/error.rs @@ -3,11 +3,44 @@ extern crate handlebars; #[macro_use] extern crate serde_json; -use std::error::Error; +use std::error::Error as StdError; -use handlebars::Handlebars; +use handlebars::{Context, Handlebars, Helper, Output, RenderContext, RenderError}; +use thiserror::Error; -fn main() -> Result<(), Box> { +#[derive(Debug, Error)] +pub enum HelperError { + #[error("db error")] + DbError, + #[error("api error")] + ApiError, +} + +/// A helper that raise error according to parameters +pub fn error_helper( + h: &Helper, + _: &Handlebars, + _: &Context, + _: &mut RenderContext, + _: &mut dyn Output, +) -> Result<(), RenderError> { + let param = h + .param(0) + .ok_or(RenderError::new("Param 0 is required for error helper."))?; + match param.value().as_str() { + Some("db") => Err(RenderError::from_error( + "helper error", + HelperError::DbError, + )), + Some("api") => Err(RenderError::from_error( + "helper error", + HelperError::ApiError, + )), + _ => Ok(()), + } +} + +fn main() -> Result<(), Box> { env_logger::init(); let mut handlebars = Handlebars::new(); @@ -36,5 +69,17 @@ fn main() -> Result<(), Box> { println!("{}", be1.source().unwrap()); println!("{:?}", be1.source().unwrap().source()); + // process helper error + handlebars.register_helper("err", Box::new(error_helper)); + let e2 = handlebars + .render_template("{{err \"db\"}}", &json!({})) + .unwrap_err(); + match e2.source().unwrap().downcast_ref::() { + Some(HelperError::DbError) => { + println!("Detected error from helper: db error",) + } + _ => {} + } + Ok(()) }