Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Supports Result for helper function #512

Open
RoCry opened this issue Jul 1, 2022 · 4 comments
Open

Supports Result for helper function #512

RoCry opened this issue Jul 1, 2022 · 4 comments
Labels

Comments

@RoCry
Copy link

RoCry commented Jul 1, 2022

In production code the helpers may returns error, we could returns the underlying error from helper when render_template.

Below are some pseudo-code:

fn query_name_by_id(id: &str) -> Result<String, DBError> {
	...
}

let result = hbr.render_template("The name is {{query_name_by_id this}}", &id);

match result {
	Ok() -> {},
	Err(e) -> {
		match e {
			Handlebars.Error(e) => // render error
			DBError(e) => // db error from query_name_by_id
			_ => {}
		}
	}
}
@sunng87
Copy link
Owner

sunng87 commented Jul 2, 2022

This is possible by down-casting error.source() to your own error type. I've made an example to demo this:

  1. Create RenderError from your own error type via RenderError::from_error: https://github.com/sunng87/handlebars-rust/blob/master/examples/error.rs#L20
  2. Down-casting the cause of render error for your own type: https://github.com/sunng87/handlebars-rust/blob/master/examples/error.rs#L78

@RoCry
Copy link
Author

RoCry commented Jul 5, 2022

The example answered my question. But it may be easier for me if:

  1. Change the handlebars_helper! to handlebars_helper_returns_result!
  2. Add a new handlebars_helper! based on 1 and keep the api exactly same with previous versions.

Is this make sense for you as well?

@sunng87
Copy link
Owner

sunng87 commented Jul 18, 2022

For helper returning Result I would recommend to use impl HelperDef and implement call_inner directly: https://docs.rs/handlebars/latest/handlebars/trait.HelperDef.html#method.call_inner

I will add an example for this use case.

@sunng87
Copy link
Owner

sunng87 commented Jul 18, 2022

You can still reuse this as an example of defining helper with API that exposes the Result: https://github.com/sunng87/handlebars-rust/blob/master/examples/error.rs#L20

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants