Skip to main content

cairn_knowledge_graph/error/
user_error.rs

1use std::error;
2use std::error::Error;
3use std::fmt;
4
5use graphblas_sparse_linear_algebra::error::{
6    SparseLinearAlgebraError, SparseLinearAlgebraErrorType,
7};
8
9#[derive(Debug)]
10pub struct UserError {
11    error_type: UserErrorType,
12    explanation: String,
13    source: Option<UserErrorSource>,
14}
15
16#[derive(Debug)]
17pub enum UserErrorSource {
18    SparseLinearAlgebra(SparseLinearAlgebraError),
19}
20
21#[derive(Debug, Clone, PartialEq)]
22pub enum UserErrorType {
23    SparseLinearAlgebra(SparseLinearAlgebraErrorType),
24    EdgeTypeDoesNotExist,
25    IndexOutOfBounds,
26    VertexAlreadyExists,
27    VertexKeyNotFound,
28    Other,
29}
30
31impl UserError {
32    pub fn new(
33        error_type: UserErrorType,
34        explanation: String,
35        source: Option<UserErrorSource>,
36    ) -> Self {
37        Self {
38            error_type,
39            explanation,
40            source,
41        }
42    }
43
44    pub fn error_type(&self) -> UserErrorType {
45        self.error_type.clone()
46    }
47    pub fn explanation(&self) -> String {
48        self.explanation.clone()
49    }
50}
51
52impl error::Error for UserError {
53    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
54        match self.source {
55            Some(ref error) => match error {
56                UserErrorSource::SparseLinearAlgebra(error) => Some(error),
57            },
58            None => None,
59        }
60    }
61}
62
63impl fmt::Display for UserError {
64    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
65        match &self.error_type {
66            // LogicErrorType::SparseLinearAlgebra(_err) => writeln!(f, "Context:\n{}", &self.context)?,
67            _ => writeln!(f, "Context:\n{}", &self.explanation)?,
68        };
69
70        match &self.source() {
71            Some(err) => writeln!(f, "Source error:\n{}", err)?,
72            &None => (),
73        }
74        Ok(())
75    }
76}
77
78impl From<SparseLinearAlgebraError> for UserError {
79    fn from(error: SparseLinearAlgebraError) -> Self {
80        Self {
81            error_type: UserErrorType::SparseLinearAlgebra(error.error_type()),
82            explanation: String::new(),
83            source: Some(UserErrorSource::SparseLinearAlgebra(error)),
84        }
85    }
86}