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