Skip to main content

require_context

Macro require_context 

Source
macro_rules! require_context {
    (@async $($body:tt)* ) => { ... };
    (@sync $($body:tt)* ) => { ... };
    (
		$(#[$attrs:meta])*
		$vis:vis async fn $name:ident
		( $($params:tt)* ) -> $return:ty
		$body:block
	) => { ... };
    (
		$(#[$attrs:meta])*
		$vis:vis fn $name:ident
		( $($params:tt)* ) -> $return:ty
		$body:block
	) => { ... };
}
Expand description

Apply this to a function, to automatically make inner errors require context. Ensures there will be a compile-time error when you forget to provide context to an error within the current function.

It is highly recommended to make use of the crate macro_rules_attribute to use it as an attribute instead of surrounding the function with the macro:

#[apply(require_context)]
fn do_something() -> Result<()> {
	Ok(())
}

Otherwise, you can use it like this:

require_context!(
	fn do_something() -> Result<()> {
		Ok(())
	}
);

Only the following kinds of functions are supported currently:

  • Function must not be const, unsafe or have an external ABI.
  • Function cannot have generics.

It is also possible to use the macro within functions, specifying sync vs async with a marker up-front:

fn do_something() -> Result<()> {
	require_context!(@sync
		let result = Ok(());
		result
	)
}