Struct TracebackError

Source
pub struct TracebackError {
    pub message: String,
    pub file: String,
    pub line: u32,
    pub parent: Option<Box<TracebackError>>,
    pub time_created: DateTime<Utc>,
    pub extra_data: Vec<Value>,
    pub project: Option<String>,
    pub computer: Option<String>,
    pub user: Option<String>,
    pub is_parent: bool,
    pub is_handled: bool,
    /* private fields */
}
Expand description

A custom error struct for handling tracebacks in Rust applications.

This struct is designed to capture error information such as the error message, the file and line where the error occurred, and additional contextual data.

§Examples

Creating a new TracebackError with a custom message:

use chrono::{DateTime, Utc};
use serde_json::Value;

let error = traceback_error::traceback!("Custom error message");
println!("{:?}", error);

§Fields

  • message: A string containing the error message.
  • file: A string containing the filename where the error occurred.
  • line: An unsigned integer representing the line number where the error occurred.
  • parent: An optional boxed TracebackError representing the parent error, if any.
  • time_created: A chrono::DateTime<Utc> indicating when the error was created.
  • extra_data: A serde_json::Value for storing additional error-related data.
  • project: An optional string representing the project name.
  • computer: An optional string representing the computer name.
  • user: An optional string representing the username.
  • is_parent: A boolean indicating if this error is considered a parent error.
  • is_handled: A boolean indicating if the error has been handled.
  • is_default: A boolean indicating if this error is the default error.

§Default Implementation

The Default trait is implemented for TracebackError, creating a default instance with the following values:

  • message: “Default message”
  • file: The current file’s name (using file!()).
  • line: The current line number (using line!()).
  • parent: None
  • time_created: The Unix epoch time.
  • extra_data: Value::Null
  • project: None
  • computer: None
  • user: None
  • is_parent: false
  • is_handled: false
  • is_default: true

§Equality Comparison

The PartialEq trait is implemented for TracebackError, allowing you to compare two TracebackError instances for equality based on their message, file, line, and other relevant fields. The is_handled and is_default fields are not considered when comparing for equality.

§Dropping Errors

Errors are automatically dropped when they go out of scope, but before they are dropped, they are handled by the TRACEBACK_ERROR_CALLBACK variable. By default, this variable is a function simply set to serialize the error and write it to a JSON file, but the default function can be changed with the set_callback! macro.

§Callback Types

The callback function can be either synchronous or asynchronous, depending on the TracebackCallbackType set globally using the TRACEBACK_ERROR_CALLBACK variable. It can be set using the set_callback! macro.

  • If TRACEBACK_ERROR_CALLBACK is Some(TracebackCallbackType::Async), an asynchronous callback function is used.
  • If TRACEBACK_ERROR_CALLBACK is Some(TracebackCallbackType::Sync), a synchronous callback function is used.
  • If TRACEBACK_ERROR_CALLBACK is None, a default callback function is used.

§Creating Errors

You can create a new TracebackError instance using the traceback! macro. Additional data can be added using the with_extra_data method, and environment variables are automatically added when the error is being handled. The additional data should be stored in a serde_json::Value struct.

§Environment Variables

The with_env_vars method populates the project, computer, and user fields with information obtained from environment variables (CARGO_PKG_NAME, COMPUTERNAME, and USERNAME, respectively) or assigns default values if the environment variables are not present.

§Tracing

Tracing can be essential for diagnosing and debugging issues in your applications. When an error occurs, you can create a TracebackError instance to record the error’s details, such as the error message, the location in the code where it occurred, and additional contextual information. Should a function return a TracebackError, it can then be re-captured to trace it even further.

Fields§

§message: String§file: String§line: u32§parent: Option<Box<TracebackError>>§time_created: DateTime<Utc>§extra_data: Vec<Value>§project: Option<String>§computer: Option<String>§user: Option<String>§is_parent: bool§is_handled: bool

Implementations§

Source§

impl TracebackError

Source

pub fn new(message: String, file: String, line: u32) -> Self

Source

pub fn with_extra_data(self, extra_data: Value) -> Self

This method allows you to attach additional data to a TracebackError instance. This extra data can be valuable when diagnosing and debugging errors, as it provides context and information related to the error.

§Parameters:
  • extra_data: A serde_json::Value containing the extra data you want to associate with the error.
§Return Value:
  • Returns a modified TracebackError instance with the provided extra_data.
§Example Usage:
use traceback_error::{traceback, TracebackError, serde_json::json};

fn main() {
    // Create a new TracebackError with extra data
    let error = traceback!().with_extra_data(json!({
        "foo": "bar",
        "a": "b",
        "1": "2"
    }));

    // Now the error instance contains the specified extra data
}

This method is useful when you want to enrich error objects with additional information relevant to the context in which the error occurred. It ensures that relevant data is available for analysis when handling errors in your Rust application.

Source

pub fn with_env_vars(self) -> Self

Adds environment variables to the TracebackError.

This method populates the project, computer, and user fields of the TracebackError based on the values of specific environment variables. If any of these environment variables are not found, default values are used, and the error message reflects that the information is unknown due to the missing environment variables.

§Example:
use traceback_error::TracebackError;

// Create a new TracebackError and populate environment variables
let error = TracebackError::new("An error occurred".to_string(), file!().to_string(), line!())
    .with_env_vars();

// The error now contains information about the project, computer, and user from
// environment variables, or default values if the environment variables are missing.
§Environment Variables Used:
  • CARGO_PKG_NAME: Used to set the project field.
  • COMPUTERNAME: Used to set the computer field.
  • USERNAME: Used to set the user field.
§Returns:

A modified TracebackError with updated project, computer, and user fields.

Source

pub fn with_parent(self, parent: TracebackError) -> Self

The with_parent method allows you to associate a parent error with the current TracebackError instance. This can be useful when you want to create a hierarchical structure of errors, where one error is considered the parent of another.

§Parameters:
  • parent: A TracebackError instance that you want to set as the parent of the current error.
§Return Value:
  • Returns a modified TracebackError instance with the specified parent error.
§Example:
use traceback_error::TracebackError;

fn main() {
    // Create a new TracebackError
    let parent_error = TracebackError::new("Parent error".to_string(), file!().to_string(), line!());

    // Create a child error with the parent error
    let child_error = TracebackError::new("Child error".to_string(), file!().to_string(), line!())
        .with_parent(parent_error);

    // Now, `child_error` has `parent_error` as its parent
}

The with_parent method is particularly useful when you want to establish relationships between errors, making it easier to understand error hierarchies and diagnose issues.

Trait Implementations§

Source§

impl Clone for TracebackError

Source§

fn clone(&self) -> TracebackError

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for TracebackError

Source§

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

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

impl Default for TracebackError

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for TracebackError

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for TracebackError

This display implementation is recursive, and will print the error and all its parents with a tab in front of each parent.

Source§

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

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

impl Drop for TracebackError

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl Error for TracebackError

1.30.0 · 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 Error for TracebackError

Source§

fn custom<T: Display>(msg: T) -> Self

Raised when there is general error when deserializing a type. Read more
Source§

fn invalid_type(unexp: Unexpected<'_>, exp: &dyn Expected) -> Self

Raised when a Deserialize receives a type different from what it was expecting. Read more
Source§

fn invalid_value(unexp: Unexpected<'_>, exp: &dyn Expected) -> Self

Raised when a Deserialize receives a value of the right type but that is wrong for some other reason. Read more
Source§

fn invalid_length(len: usize, exp: &dyn Expected) -> Self

Raised when deserializing a sequence or map and the input data contains too many or too few elements. Read more
Source§

fn unknown_variant(variant: &str, expected: &'static [&'static str]) -> Self

Raised when a Deserialize enum type received a variant with an unrecognized name.
Source§

fn unknown_field(field: &str, expected: &'static [&'static str]) -> Self

Raised when a Deserialize struct type received a field with an unrecognized name.
Source§

fn missing_field(field: &'static str) -> Self

Raised when a Deserialize struct type expected to receive a required field with a particular name but that field was not present in the input.
Source§

fn duplicate_field(field: &'static str) -> Self

Raised when a Deserialize struct type received more than one of the same field.
Source§

impl PartialEq for TracebackError

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Serialize for TracebackError

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,