Error

Struct Error 

Source
pub struct Error { /* private fields */ }
Expand description

Rich application error preserving domain code, taxonomy and metadata.

Implementations§

Source§

impl AppError

Source

pub fn not_found(msg: impl Into<Cow<'static, str>>) -> Self

Build a NotFound error.

Source

pub fn validation(msg: impl Into<Cow<'static, str>>) -> Self

Build a Validation error.

Source

pub fn unauthorized(msg: impl Into<Cow<'static, str>>) -> Self

Build an Unauthorized error.

Source

pub fn forbidden(msg: impl Into<Cow<'static, str>>) -> Self

Build a Forbidden error.

Source

pub fn conflict(msg: impl Into<Cow<'static, str>>) -> Self

Build a Conflict error.

Source

pub fn bad_request(msg: impl Into<Cow<'static, str>>) -> Self

Build a BadRequest error.

Source

pub fn rate_limited(msg: impl Into<Cow<'static, str>>) -> Self

Build a RateLimited error.

Source

pub fn telegram_auth(msg: impl Into<Cow<'static, str>>) -> Self

Build a TelegramAuth error.

Source

pub fn internal(msg: impl Into<Cow<'static, str>>) -> Self

Build an Internal error.

Source

pub fn service(msg: impl Into<Cow<'static, str>>) -> Self

Build a Service error (generic server-side service failure).

Source

pub fn database(msg: Option<Cow<'static, str>>) -> Self

Build a Database error with an optional message.

This constructor accepts a pre-built Cow so callers that already manage ownership can pass either borrowed or owned strings. When you have plain string data, prefer AppError::database_with_message.

use masterror::AppError;

let err = AppError::database(None);
assert!(err.message.is_none());
Source

pub fn database_with_message(msg: impl Into<Cow<'static, str>>) -> Self

Build a Database error with a message.

Convenience wrapper around AppError::database for the common case where you start from a plain string-like value.

use masterror::AppError;

let err = AppError::database_with_message("db down");
assert_eq!(err.message.as_deref(), Some("db down"));
Source

pub fn config(msg: impl Into<Cow<'static, str>>) -> Self

Build a Config error.

Source

pub fn turnkey(msg: impl Into<Cow<'static, str>>) -> Self

Build a Turnkey error.

Source

pub fn timeout(msg: impl Into<Cow<'static, str>>) -> Self

Build a Timeout error.

Source

pub fn network(msg: impl Into<Cow<'static, str>>) -> Self

Build a Network error.

Source

pub fn dependency_unavailable(msg: impl Into<Cow<'static, str>>) -> Self

Build a DependencyUnavailable error.

Source

pub fn service_unavailable(msg: impl Into<Cow<'static, str>>) -> Self

Backward-compatible alias; routes to DependencyUnavailable.

Source

pub fn serialization(msg: impl Into<Cow<'static, str>>) -> Self

Build a Serialization error.

Source

pub fn deserialization(msg: impl Into<Cow<'static, str>>) -> Self

Build a Deserialization error.

Source

pub fn external_api(msg: impl Into<Cow<'static, str>>) -> Self

Build an ExternalApi error.

Source

pub fn queue(msg: impl Into<Cow<'static, str>>) -> Self

Build a Queue error.

Source

pub fn cache(msg: impl Into<Cow<'static, str>>) -> Self

Build a Cache error.

Source§

impl Error

Source

pub fn new(kind: AppErrorKind, msg: impl Into<Cow<'static, str>>) -> Self

Create a new Error with a kind and message.

This is equivalent to Error::with, provided for API symmetry and to keep doctests readable.

§Examples
use masterror::{AppError, AppErrorKind};
let err = AppError::new(AppErrorKind::BadRequest, "invalid payload");
assert!(err.message.is_some());
Source

pub fn with(kind: AppErrorKind, msg: impl Into<Cow<'static, str>>) -> Self

Create an error with the given kind and message.

Prefer named helpers (e.g. Error::not_found) where it clarifies intent.

Source

pub fn bare(kind: AppErrorKind) -> Self

Create a message-less error with the given kind.

Useful when the kind alone conveys sufficient information to the client.

Source

pub fn with_code(self, code: AppCode) -> Self

Override the machine-readable AppCode.

Source

pub fn with_retry_after_secs(self, secs: u64) -> Self

Attach retry advice to the error.

When mapped to HTTP, this becomes the Retry-After header.

Source

pub fn with_www_authenticate(self, value: impl Into<String>) -> Self

Attach a WWW-Authenticate challenge string.

Source

pub fn with_field(self, field: Field) -> Self

Attach additional metadata to the error.

Source

pub fn with_fields(self, fields: impl IntoIterator<Item = Field>) -> Self

Extend metadata from an iterator of fields.

Source

pub fn redact_field(self, name: &'static str, redaction: FieldRedaction) -> Self

Override the redaction policy for a stored metadata field.

Source

pub fn with_metadata(self, metadata: Metadata) -> Self

Replace metadata entirely.

Source

pub fn redactable(self) -> Self

Mark the message as redactable.

Source

pub fn with_context(self, context: impl Into<ContextAttachment>) -> Self

Attach upstream diagnostics using with_source or an existing Arc.

This is the preferred alias for capturing upstream errors. It accepts either an owned error implementing core::error::Error or a shared Arc produced by other APIs, reusing the allocation when possible.

§Examples
use masterror::AppError;

let err = AppError::service("downstream degraded")
    .with_context(std::io::Error::new(std::io::ErrorKind::Other, "boom"));
assert!(err.source_ref().is_some());
Source

pub fn with_source(self, source: impl CoreError + Send + Sync + 'static) -> Self

Attach a source error for diagnostics.

Prefer with_context when capturing upstream diagnostics without additional Arc allocations.

Source

pub fn with_source_arc( self, source: Arc<dyn CoreError + Send + Sync + 'static>, ) -> Self

Attach a shared source error without cloning the underlying Arc.

§Examples
use std::sync::Arc;

use masterror::{AppError, AppErrorKind};

let source = Arc::new(std::io::Error::new(std::io::ErrorKind::Other, "boom"));
let err = AppError::internal("boom").with_source_arc(source.clone());
assert!(err.source_ref().is_some());
assert_eq!(Arc::strong_count(&source), 2);
Source

pub fn with_backtrace(self, backtrace: Backtrace) -> Self

Attach a captured backtrace.

Source

pub fn with_details_text(self, details: impl Into<String>) -> Self

Available on non-crate feature serde_json only.

Attach plain-text details for client payloads.

The text is omitted from responses when the error is redactable.

§Examples
use masterror::{AppError, AppErrorKind};

let err = AppError::new(AppErrorKind::Internal, "boom").with_details_text("retry later");
assert!(err.details.is_some());
Source

pub fn metadata(&self) -> &Metadata

Borrow the attached metadata.

Source

pub fn backtrace(&self) -> Option<&Backtrace>

Borrow the backtrace, capturing it lazily when the backtrace feature is enabled.

Source

pub fn source_ref(&self) -> Option<&(dyn CoreError + Send + Sync + 'static)>

Borrow the source if present.

Source

pub fn render_message(&self) -> Cow<'_, str>

Human-readable message or the kind fallback.

Source

pub fn log(&self)

Emit telemetry (tracing event, metrics counter, backtrace capture).

Downstream code can call this to guarantee telemetry after mutating the error. It is automatically invoked by constructors and conversions.

Trait Implementations§

Source§

impl Debug for Error

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Deref for Error

Source§

type Target = ErrorInner

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.
Source§

impl DerefMut for Error

Source§

fn deref_mut(&mut self) -> &mut Self::Target

Mutably dereferences the value.
Source§

impl Display for Error

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult

Formats the value using the given formatter. Read more
Source§

impl Error for Error

Source§

fn source(&self) -> Option<&(dyn CoreError + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl From<&Error> for ErrorResponse

Source§

fn from(err: &AppError) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for AppError

Available on crate feature std only.

Map std::io::Error to an internal application error.

Rationale: I/O failures are infrastructure-level and should not leak driver-specific details to clients. The message is preserved for observability, but the public-facing kind is always Internal.

use std::io::{self, ErrorKind};

use masterror::{AppError, AppErrorKind};

let io_err = io::Error::from(ErrorKind::Other);
let app_err: AppError = io_err.into();
assert!(matches!(app_err.kind, AppErrorKind::Internal));
Source§

fn from(err: IoError) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for ErrorResponse

Source§

fn from(err: AppError) -> Self

Converts to this type from the input type.
Source§

impl From<String> for AppError

Map a plain String to a client error (BadRequest).

Handy for quick validation paths without the validator feature. Prefer structured validation for complex DTOs, but this covers simple cases.

use masterror::{AppError, AppErrorKind, AppResult};

fn check(name: &str) -> AppResult<()> {
    if name.is_empty() {
        return Err(String::from("name must not be empty").into());
    }
    Ok(())
}

let err = check("").unwrap_err();
assert!(matches!(err.kind, AppErrorKind::BadRequest));
Source§

fn from(value: String) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl Freeze for Error

§

impl !RefUnwindSafe for Error

§

impl Send for Error

§

impl Sync for Error

§

impl Unpin for Error

§

impl !UnwindSafe for Error

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.