1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
use crate::log::log_error;
use std::fmt::Debug;
/// Handles a given [`libcnb::Error`] in a consistent style.
///
/// This function is intended to be used inside [`libcnb::Buildpack::on_error`].
///
/// It outputs generic libcnb errors in a consistent style using the [logging functions](log_error) from this
/// crate. Buildpack specific errors are handled by the passed custom handler.
///
/// # Example:
/// ```
/// use libcnb::build::{BuildContext, BuildResult};
/// use libcnb::Buildpack;
/// use libcnb::detect::{DetectContext, DetectResult};
/// use libcnb::generic::{GenericMetadata, GenericPlatform};
/// use libherokubuildpack::log::log_error;
/// use libherokubuildpack::error::on_error;
///
/// #[derive(Debug)]
/// enum FooBuildpackError {
/// CannotExecuteFooBuildTool(std::io::Error),
/// InvalidFooDescriptorToml
/// }
///
/// fn on_foo_buildpack_error(e: FooBuildpackError) {
/// match e {
/// FooBuildpackError::InvalidFooDescriptorToml => {
/// log_error("Invalid foo.toml", "Your app's foo.toml is invalid!");
/// }
/// FooBuildpackError::CannotExecuteFooBuildTool(inner) => {
/// log_error("Couldn't execute foo build tool", format!("Cause: {}", &inner));
/// }
/// }
/// }
///
/// struct FooBuildpack;
///
/// impl Buildpack for FooBuildpack {
/// type Platform = GenericPlatform;
/// type Metadata = GenericMetadata;
/// type Error = FooBuildpackError;
///
/// // Omitted detect and build implementations...
/// # fn detect(&self, context: DetectContext<Self>) -> libcnb::Result<DetectResult, Self::Error> {
/// # unimplemented!()
/// # }
/// #
/// # fn build(&self, context: BuildContext<Self>) -> libcnb::Result<BuildResult, Self::Error> {
/// # unimplemented!()
/// # }
///
/// fn on_error(&self, error: libcnb::Error<Self::Error>) {
/// on_error(on_foo_buildpack_error, error)
/// }
/// }
/// ```
pub fn on_error<F, E>(f: F, error: libcnb::Error<E>)
where
E: Debug,
F: Fn(E),
{
match error {
libcnb::Error::BuildpackError(buildpack_error) => f(buildpack_error),
libcnb_error => {
log_error("Internal Buildpack Error", libcnb_error.to_string());
}
}
}