Skip to main content

DecimalError

Enum DecimalError 

Source
pub enum DecimalError {
    InvalidValue {
        value: f64,
        reason: String,
    },
    ArithmeticError {
        operation: String,
        reason: String,
    },
    ConversionError {
        from_type: String,
        to_type: String,
        reason: String,
    },
    OutOfBounds {
        value: f64,
        min: f64,
        max: f64,
    },
    InvalidPrecision {
        precision: i32,
        reason: String,
    },
    ExpirationDate(ExpirationDateError),
    Overflow {
        operation: &'static str,
        lhs: Decimal,
        rhs: Decimal,
    },
}
Expand description

§Decimal Error Management

Represents errors that can occur during decimal operations in financial calculations. This enum provides a structured way to handle various error conditions that may arise when working with decimal values, including validation, arithmetic operations, conversions, and precision issues.

§Use Cases

  • Financial calculations requiring strict decimal precision
  • Currency and monetary value operations
  • Option pricing models where precision is critical
  • Risk management calculations

§Error Propagation

These errors are typically wrapped in DecimalResult and propagated through the application’s calculation pipeline.

§Variants

  • InvalidValue - Handles errors when a value cannot be represented as a valid decimal
  • ArithmeticError - Handles errors during mathematical operations
  • ConversionError - Handles errors when converting between different decimal representations
  • OutOfBounds - Handles errors when a value exceeds defined limits
  • InvalidPrecision - Handles errors related to decimal precision settings

§Example Usage

use optionstratlib_core::error::DecimalError;

fn validate_decimal(value: f64) -> Result<(), DecimalError> {
    if value.is_nan() {
        return Err(DecimalError::InvalidValue {
            value,
            reason: "Value cannot be NaN".to_string(),
        });
    }
     
    if value < 0.0 || value > 100.0 {
        return Err(DecimalError::OutOfBounds {
            value,
            min: 0.0,
            max: 100.0,
        });
    }
     
    Ok(())
}

Variants§

§

InvalidValue

Error when attempting to create a decimal from an invalid value

Occurs when a value cannot be properly represented as a decimal, such as when it’s NaN, infinity, or otherwise unsuitable for financial calculations.

Fields

§value: f64

The problematic value that caused the error

§reason: String

Detailed explanation of why the value is invalid

§

ArithmeticError

Error when performing decimal arithmetic operations

Occurs during mathematical operations such as addition, subtraction, multiplication, or division when the operation cannot be completed correctly (e.g., division by zero, overflow).

Fields

§operation: String

The operation that failed (e.g., “addition”, “division”)

§reason: String

Detailed explanation of why the operation failed

§

ConversionError

Error when converting between decimal types

Occurs when a decimal value cannot be correctly converted from one representation to another, such as between different precision levels or between different decimal formats.

Fields

§from_type: String

The source type being converted from

§to_type: String

The destination type being converted to

§reason: String

Detailed explanation of why the conversion failed

§

OutOfBounds

Error when a decimal value exceeds its bounds

Occurs when a decimal value falls outside of acceptable minimum or maximum values for a specific calculation context.

Fields

§value: f64

The value that is out of bounds

§min: f64

The minimum acceptable value

§max: f64

The maximum acceptable value

§

InvalidPrecision

Error when decimal precision is invalid

Occurs when an operation specifies or results in an invalid precision level that cannot be properly handled.

Fields

§precision: i32

The problematic precision value

§reason: String

Detailed explanation of why the precision is invalid

§

ExpirationDate(ExpirationDateError)

Expiration-date conversion error surfaced during decimal operations.

§

Overflow

Error when a Decimal arithmetic operation overflows the representable range.

Emitted by the crate-private d_add / d_sub / d_mul / d_div helpers in crate::model::decimal when the underlying Decimal::checked_* call returns None. The operation tag is a short, static identifier describing the call-site (for example "pricing::black_scholes::discount_strike") so failures can be traced back to their kernel without walking the call stack.

The operands are captured verbatim for post-mortem debugging and are included in the formatted error output (see the #[error] template below). This DecimalError variant is propagated across domain modules through the existing #[from] cascade, so the operand values will appear in any log or wrapper-error string produced downstream. Callers that need to redact them for production logging should match on the Overflow variant explicitly and reformat rather than rely on the default Display.

Fields

§operation: &'static str

Short static tag identifying the call-site.

§lhs: Decimal

Left-hand operand of the failed arithmetic.

§rhs: Decimal

Right-hand operand of the failed arithmetic.

Implementations§

Source§

impl DecimalError

Helper methods for creating common decimal errors

This implementation provides convenient factory methods to create standardized instances of DecimalError for common error scenarios in decimal operations. These methods help maintain consistency in error creation across the codebase and simplify the construction of descriptive error instances.

§Example

use optionstratlib_core::error::DecimalError;
// Creating an invalid value error
let err = DecimalError::invalid_value(12.34, "Value exceeds maximum allowed");

// Creating an arithmetic error
let div_err = DecimalError::arithmetic_error("division", "Division by zero");
Source

pub fn invalid_value(value: f64, reason: &str) -> Self

Creates a new InvalidValue error

Used when a decimal value fails validation due to being outside accepted ranges or otherwise inappropriate for the context.

§Parameters
  • value - The problematic floating-point value
  • reason - Explanation of why the value is invalid
§Returns

A new DecimalError::InvalidValue instance

Source

pub fn arithmetic_error(operation: &str, reason: &str) -> Self

Creates a new ArithmeticError error

Used when a mathematical operation on decimal values fails, such as division by zero, overflow, or underflow.

§Parameters
  • operation - The name of the operation that failed (e.g., “addition”, “division”)
  • reason - Explanation of why the operation failed
§Returns

A new DecimalError::ArithmeticError instance

Source

pub fn conversion_error(from_type: &str, to_type: &str, reason: &str) -> Self

Creates a new ConversionError error

Used when conversion between decimal types or from/to other number types fails due to compatibility or range issues.

§Parameters
  • from_type - The source type being converted from
  • to_type - The destination type being converted to
  • reason - Explanation of why the conversion failed
§Returns

A new DecimalError::ConversionError instance

Source

pub fn out_of_bounds(value: f64, min: f64, max: f64) -> Self

Creates a new OutOfBounds error

Used when a decimal value falls outside of specified minimum and maximum bounds.

§Parameters
  • value - The out-of-bounds floating-point value
  • min - The lower bound (inclusive) of the valid range
  • max - The upper bound (inclusive) of the valid range
§Returns

A new DecimalError::OutOfBounds instance

Source

pub fn invalid_precision(precision: i32, reason: &str) -> Self

Creates a new InvalidPrecision error

Used when a specified decimal precision is invalid, such as being negative, too large, or otherwise inappropriate for the context.

§Parameters
  • precision - The problematic precision value
  • reason - Explanation of why the precision is invalid
§Returns

A new DecimalError::InvalidPrecision instance

Source

pub fn overflow(operation: &'static str, lhs: Decimal, rhs: Decimal) -> Self

Creates a new Overflow error for a failed checked arithmetic operation.

Used by the crate-private d_add / d_sub / d_mul / d_div helpers to surface an overflow of the underlying Decimal::checked_* call with full operand context.

§Parameters
  • operation - Short static tag identifying the call-site (for example "pricing::black_scholes::discount_strike").
  • lhs - Left-hand operand of the failed arithmetic.
  • rhs - Right-hand operand of the failed arithmetic.
§Returns

A new DecimalError::Overflow instance.

Trait Implementations§

Source§

impl Debug for DecimalError

Source§

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

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

impl Display for DecimalError

Source§

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

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

impl Error for DecimalError

Source§

fn source(&self) -> Option<&(dyn Error + '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<DecimalError> for OptionsError

Source§

fn from(source: DecimalError) -> Self

Converts to this type from the input type.
Source§

impl From<DecimalError> for PositionError

Source§

fn from(source: DecimalError) -> Self

Converts to this type from the input type.
Source§

impl From<ExpirationDateError> for DecimalError

Source§

fn from(err: ExpirationDateError) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

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> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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<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 = !

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

fn try_from(value: U) -> Result<T, !>

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.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more