orion_error/core/
context.rs1use derive_getters::Getters;
2use std::fmt::Display;
3use thiserror::Error;
4
5#[derive(Debug, Clone, Getters, Default)]
6pub struct WithContext {
7 target: Option<String>,
8 context: ErrContext,
9}
10
11impl WithContext {
12 pub fn new() -> Self {
13 Self {
14 target: None,
15 context: ErrContext::default(),
16 }
17 }
18 pub fn want<S: Into<String>>(target: S) -> Self {
19 Self {
20 target: Some(target.into()),
21 context: ErrContext::default(),
22 }
23 }
24 pub fn with<S1: Into<String>, S2: Into<String>>(&mut self, key: S1, val: S2) {
25 self.context.items.push((key.into(), val.into()));
26 }
27}
28
29impl From<String> for WithContext {
30 fn from(value: String) -> Self {
31 Self {
32 target: Some(value),
33 context: ErrContext::default(),
34 }
35 }
36}
37
38impl From<&str> for WithContext {
39 fn from(value: &str) -> Self {
40 Self {
41 target: Some(value.to_string()),
42 context: ErrContext::default(),
43 }
44 }
45}
46
47impl From<&WithContext> for WithContext {
48 fn from(value: &WithContext) -> Self {
49 value.clone()
50 }
51}
52
53#[derive(Default, Error, Debug, Clone, PartialEq)]
54pub struct ErrContext {
55 pub items: Vec<(String, String)>,
56}
57
58pub trait ContextAdd<T> {
59 fn add_context(&mut self, val: T);
60}
61
62impl Display for ErrContext {
63 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64 if !self.items.is_empty() {
65 writeln!(f, "\nerror context:")?;
66 }
67 for (k, v) in &self.items {
68 writeln!(f, "\t{} : {}", k, v)?;
69 }
70 Ok(())
71 }
72}