1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
/*!
Contains error and result types for all the model functions.
*/

use std::{fmt::Display, num::TryFromIntError};

use backtrace::Backtrace;
use headless_lms_utils::error::{backend_error::BackendError, util_error::UtilError};
use tracing_error::SpanTrace;
use uuid::Uuid;

/**
Used as the result types for all models.

See also [ModelError] for documentation on how to return errors from models.
*/
pub type ModelResult<T> = Result<T, ModelError>;

pub trait TryToOptional<T, E> {
    fn optional(self) -> Result<Option<T>, E>
    where
        Self: Sized;
}

impl<T> TryToOptional<T, ModelError> for ModelResult<T> {
    fn optional(self) -> Result<Option<T>, ModelError> {
        match self {
            Ok(val) => Ok(Some(val)),
            Err(err) => {
                if err.error_type == ModelErrorType::RecordNotFound {
                    Ok(None)
                } else {
                    Err(err)
                }
            }
        }
    }
}

/**
Error type used by all models. Used as the error type in [ModelError], which is used by all the controllers in the application.

All the information in the error is meant to be seen by the user. The type of error is determined by the [ModelErrorType] enum, which is stored inside this struct.

## Examples

### Usage without source error

```no_run
# use headless_lms_models::prelude::*;
# fn random_function() -> ModelResult<()> {
#    let erroneous_condition = 1 == 1;
if erroneous_condition {
    return Err(ModelError::new(
        ModelErrorType::PreconditionFailed,
        "The user has not enrolled to this course".to_string(),
        None,
    ));
}
# Ok(())
# }
```

### Usage with a source error

Used when calling a function that returns an error that cannot be automatically converted to an ModelError. (See `impl From<X>` implementations on this struct.)

```no_run
# use headless_lms_models::prelude::*;
# fn some_function_returning_an_error() -> ModelResult<()> {
#    return Err(ModelError::new(
#        ModelErrorType::PreconditionFailed,
#        "The user has not enrolled to this course".to_string(),
#        None,
#    ));
# }
#
# fn random_function() -> ModelResult<()> {
#    let erroneous_condition = 1 == 1;
some_function_returning_an_error().map_err(|original_error| {
    ModelError::new(
        ModelErrorType::Generic,
        "Everything went wrong".to_string(),
        Some(original_error.into()),
    )
})?;
# Ok(())
# }
```
*/
#[derive(Debug)]
pub struct ModelError {
    error_type: ModelErrorType,
    message: String,
    /// Original error that caused this error.
    source: Option<anyhow::Error>,
    /// A trace of tokio tracing spans, generated automatically when the error is generated.
    span_trace: SpanTrace,
    /// Stack trace, generated automatically when the error is created.
    backtrace: Backtrace,
}

impl std::error::Error for ModelError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.source.as_ref().and_then(|o| o.source())
    }

    fn cause(&self) -> Option<&dyn std::error::Error> {
        self.source()
    }
}

impl Display for ModelError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "ModelError {:?} {:?}", self.error_type, self.message)
    }
}

impl BackendError for ModelError {
    type ErrorType = ModelErrorType;

    fn new(
        error_type: Self::ErrorType,
        message: String,
        source_error: Option<anyhow::Error>,
    ) -> Self {
        Self::new_with_traces(
            error_type,
            message,
            source_error,
            Backtrace::new(),
            SpanTrace::capture(),
        )
    }

    fn backtrace(&self) -> Option<&Backtrace> {
        Some(&self.backtrace)
    }

    fn error_type(&self) -> &Self::ErrorType {
        &self.error_type
    }

    fn message(&self) -> &str {
        &self.message
    }

    fn span_trace(&self) -> &SpanTrace {
        &self.span_trace
    }

    fn new_with_traces(
        error_type: Self::ErrorType,
        message: String,
        source_error: Option<anyhow::Error>,
        backtrace: Backtrace,
        span_trace: SpanTrace,
    ) -> Self {
        Self {
            error_type,
            message,
            source: source_error,
            span_trace,
            backtrace,
        }
    }
}

/// The type of [ModelError] that occured.
#[derive(Debug, PartialEq, Eq)]
pub enum ModelErrorType {
    RecordNotFound,
    NotFound,
    DatabaseConstraint {
        constraint: String,
        description: &'static str,
    },
    PreconditionFailed,
    PreconditionFailedWithCMSAnchorBlockId {
        id: Uuid,
        description: &'static str,
    },
    InvalidRequest,
    Conversion,
    Database,
    Json,
    Util,
    Generic,
}

impl From<sqlx::Error> for ModelError {
    fn from(err: sqlx::Error) -> Self {
        match &err {
            sqlx::Error::RowNotFound => ModelError::new(
                ModelErrorType::RecordNotFound,
                err.to_string(),
                Some(err.into()),
            ),
            sqlx::Error::Database(db_err) => {
                if let Some(constraint) = db_err.constraint() {
                    match constraint {
                        "email_templates_subject_check" => ModelError::new(
                            ModelErrorType::DatabaseConstraint {
                                constraint: constraint.to_string(),
                                description: "Subject must not be null",
                            },
                            err.to_string(),
                            Some(err.into()),
                        ),
                        "user_details_email_check" => ModelError::new(
                            ModelErrorType::DatabaseConstraint {
                                constraint: constraint.to_string(),
                                description: "Email must contain an '@' symbol.",
                            },
                            err.to_string(),
                            Some(err.into()),
                        ),
                        _ => ModelError::new(
                            ModelErrorType::Database,
                            err.to_string(),
                            Some(err.into()),
                        ),
                    }
                } else {
                    ModelError::new(ModelErrorType::Database, err.to_string(), Some(err.into()))
                }
            }
            _ => ModelError::new(ModelErrorType::Database, err.to_string(), Some(err.into())),
        }
    }
}

impl std::convert::From<TryFromIntError> for ModelError {
    fn from(source: TryFromIntError) -> Self {
        ModelError::new(
            ModelErrorType::Conversion,
            source.to_string(),
            Some(source.into()),
        )
    }
}

impl std::convert::From<serde_json::Error> for ModelError {
    fn from(source: serde_json::Error) -> Self {
        ModelError::new(
            ModelErrorType::Json,
            source.to_string(),
            Some(source.into()),
        )
    }
}

impl std::convert::From<UtilError> for ModelError {
    fn from(source: UtilError) -> Self {
        ModelError::new(
            ModelErrorType::Util,
            source.to_string(),
            Some(source.into()),
        )
    }
}

impl From<anyhow::Error> for ModelError {
    fn from(err: anyhow::Error) -> ModelError {
        Self::new(ModelErrorType::Conversion, err.to_string(), Some(err))
    }
}

impl From<url::ParseError> for ModelError {
    fn from(err: url::ParseError) -> ModelError {
        Self::new(ModelErrorType::Generic, err.to_string(), Some(err.into()))
    }
}

#[cfg(test)]
mod test {
    use uuid::Uuid;

    use super::*;
    use crate::{email_templates::EmailTemplateNew, test_helper::*, PKeyPolicy};

    #[tokio::test]
    async fn email_templates_check() {
        insert_data!(:tx, :user, :org, :course, :instance);

        let err = crate::email_templates::insert_email_template(
            tx.as_mut(),
            instance.id,
            EmailTemplateNew {
                name: "".to_string(),
            },
            Some(""),
        )
        .await
        .unwrap_err();
        if let ModelErrorType::DatabaseConstraint { constraint, .. } = err.error_type {
            assert_eq!(constraint, "email_templates_subject_check");
        } else {
            panic!("wrong error variant")
        }
    }

    #[tokio::test]
    async fn user_details_email_check() {
        let mut conn = Conn::init().await;
        let mut tx = conn.begin().await;
        let err = crate::users::insert(
            tx.as_mut(),
            PKeyPolicy::Fixed(Uuid::parse_str("92c2d6d6-e1b8-4064-8c60-3ae52266c62c").unwrap()),
            "invalid email",
            None,
            None,
        )
        .await
        .unwrap_err();
        if let ModelErrorType::DatabaseConstraint { constraint, .. } = err.error_type {
            assert_eq!(constraint, "user_details_email_check");
        } else {
            panic!("wrong error variant")
        }
    }
}