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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
/*!
Contains error and result types for all the controllers.
*/

use std::{error::Error, fmt::Write};

use crate::domain::authorization::AuthorizedResponse;
use actix_web::{
    error,
    http::{header::ContentType, StatusCode},
    HttpResponse, HttpResponseBuilder,
};
use backtrace::Backtrace;
use derive_more::Display;
use headless_lms_models::{ModelError, ModelErrorType};
use headless_lms_utils::error::{
    backend_error::BackendError, backtrace_formatter::format_backtrace, util_error::UtilError,
};
use serde::{Deserialize, Serialize};
use tracing_error::SpanTrace;
#[cfg(feature = "ts_rs")]
use ts_rs::TS;
use uuid::Uuid;

/**
Used as the result types for all controllers.
Only put information here that you want to be visible to users.

See also [ControllerError] for documentation on how to return errors from controllers.
*/
pub type ControllerResult<T, E = ControllerError> = std::result::Result<AuthorizedResponse<T>, E>;

/// The type of [ControllerError] that occured.
#[derive(Debug, Display, Serialize, Deserialize)]
pub enum ControllerErrorType {
    /// HTTP status code 500.
    #[display(fmt = "Internal server error")]
    InternalServerError,

    /// HTTP status code 400.
    #[display(fmt = "Bad request")]
    BadRequest,

    /// HTTP status code 400.
    #[display(fmt = "Bad request")]
    BadRequestWithData(ErrorData),

    /// HTTP status code 404.
    #[display(fmt = "Not found")]
    NotFound,

    /// HTTP status code 401. Needs to log in.
    #[display(fmt = "Unauthorized")]
    Unauthorized,

    /// HTTP status code 403. Is logged in but is not allowed to access the resource.
    #[display(fmt = "Forbidden")]
    Forbidden,
}

/**
Represents error messages that are sent in responses. Used as the error type in [ControllerError], 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 [ControllerErrorType] enum, which is stored inside this struct. The type of the error determines which HTTP status code will be sent to the user.

## Examples

### Usage without source error

```no_run
# use headless_lms_server::prelude::*;
# fn random_function() -> ControllerResult<web::Json<()>> {
#    let token = skip_authorize();
#    let erroneous_condition = 1 == 1;
if erroneous_condition {
    return Err(ControllerError::new(
        ControllerErrorType::BadRequest,
        "Cannot create a new account when signed in.".to_string(),
        None,
    ));
}
# token.authorized_ok(web::Json(()))
# }
```

### Usage with a source error

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

```no_run
# use headless_lms_server::prelude::*;
# fn some_function_returning_an_error() -> ControllerResult<web::Json<()>> {
#    return Err(ControllerError::new(
#         ControllerErrorType::BadRequest,
#         "Cannot create a new account when signed in.".to_string(),
#         None,
#     ));
# }
#
# fn random_function() -> ControllerResult<web::Json<()>> {
#    let token = skip_authorize();
#    let erroneous_condition = 1 == 1;
some_function_returning_an_error().map_err(|original_error| {
    ControllerError::new(
        ControllerErrorType::InternalServerError,
        "Could not read file".to_string(),
        Some(original_error.into()),
    )
})?;
# token.authorized_ok(web::Json(()))
# }
```

### Example HTTP response from an error

```json
{
    "title": "Internal Server Error",
    "message": "pool timed out while waiting for an open connection",
    "source": "source of error"
}
```
*/
pub struct ControllerError {
    error_type: <ControllerError as BackendError>::ErrorType,
    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,
}

/// Custom formatter so that errors that get printed to the console are easy-to-read with proper context where the error is coming from.
impl std::fmt::Debug for ControllerError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ControllerError")
            .field("error_type", &self.error_type)
            .field("message", &self.message)
            .field("source", &self.source)
            .finish()?;

        f.write_str("\n\nOperating system thread stack backtrace:\n")?;
        format_backtrace(&self.backtrace, f)?;

        f.write_str("\n\nTokio tracing span trace:\n")?;
        f.write_fmt(format_args!("{}\n", &self.span_trace))?;

        Ok(())
    }
}

impl std::error::Error for ControllerError {
    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 std::fmt::Display for ControllerError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "ControllerError {:?} {:?}",
            self.error_type, self.message
        )
    }
}

impl BackendError for ControllerError {
    type ErrorType = ControllerErrorType;

    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,
        }
    }
}

#[derive(Debug, Serialize, Deserialize, Clone)]
#[cfg_attr(feature = "ts_rs", derive(TS))]
#[serde(rename_all = "snake_case")]
pub enum ErrorData {
    BlockId(Uuid),
}

/// The format all error messages from the API is in
#[derive(Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "ts_rs", derive(TS))]
pub struct ErrorResponse {
    pub title: String,
    pub message: String,
    pub source: Option<String>,
    pub data: Option<ErrorData>,
}

impl error::ResponseError for ControllerError {
    fn error_response(&self) -> HttpResponse {
        if let ControllerErrorType::InternalServerError = &self.error_type {
            let mut err_string = String::new();
            let mut source = Some(&self as &dyn Error);
            while let Some(err) = source {
                let res = write!(err_string, "{}\n    ", err);
                if let Err(e) = res {
                    error!(
                        "Error occured while trying to construct error source string: {}",
                        e
                    );
                }
                source = err.source();
            }
            error!("Internal server error: {}", err_string);
        }

        let status = self.status_code();
        let error_data = if let ControllerErrorType::BadRequestWithData(data) = &self.error_type {
            Some(data.clone())
        } else {
            None
        };

        let source = self.source();
        let source_message = source.map(|o| o.to_string());

        let error_response = ErrorResponse {
            title: status
                .canonical_reason()
                .map(|o| o.to_string())
                .unwrap_or_else(|| status.to_string()),
            message: self.message.clone(),
            source: source_message,
            data: error_data,
        };

        HttpResponseBuilder::new(status)
            .append_header(ContentType::json())
            .body(serde_json::to_string(&error_response).unwrap_or_else(|_| r#"{"title": "Internal server error", "message": "Error occured while formatting error message."}"#.to_string()))
    }

    fn status_code(&self) -> StatusCode {
        match self.error_type {
            ControllerErrorType::InternalServerError => StatusCode::INTERNAL_SERVER_ERROR,
            ControllerErrorType::BadRequest => StatusCode::BAD_REQUEST,
            ControllerErrorType::BadRequestWithData(_) => StatusCode::BAD_REQUEST,
            ControllerErrorType::NotFound => StatusCode::NOT_FOUND,
            ControllerErrorType::Unauthorized => StatusCode::UNAUTHORIZED,
            ControllerErrorType::Forbidden => StatusCode::FORBIDDEN,
        }
    }
}

impl From<anyhow::Error> for ControllerError {
    fn from(err: anyhow::Error) -> ControllerError {
        if let Some(sqlx::Error::RowNotFound) = err.downcast_ref::<sqlx::Error>() {
            return Self::new(ControllerErrorType::NotFound, err.to_string(), Some(err));
        }

        Self::new(
            ControllerErrorType::InternalServerError,
            err.to_string(),
            Some(err),
        )
    }
}

impl From<uuid::Error> for ControllerError {
    fn from(err: uuid::Error) -> ControllerError {
        Self::new(
            ControllerErrorType::BadRequest,
            err.to_string(),
            Some(err.into()),
        )
    }
}

impl From<sqlx::Error> for ControllerError {
    fn from(err: sqlx::Error) -> ControllerError {
        Self::new(
            ControllerErrorType::InternalServerError,
            err.to_string(),
            Some(err.into()),
        )
    }
}

impl From<git2::Error> for ControllerError {
    fn from(err: git2::Error) -> ControllerError {
        Self::new(
            ControllerErrorType::InternalServerError,
            err.to_string(),
            Some(err.into()),
        )
    }
}

impl From<actix_web::Error> for ControllerError {
    fn from(err: actix_web::Error) -> Self {
        Self::new(
            ControllerErrorType::InternalServerError,
            err.to_string(),
            None,
        )
    }
}

impl From<actix_multipart::MultipartError> for ControllerError {
    fn from(err: actix_multipart::MultipartError) -> Self {
        Self::new(
            ControllerErrorType::InternalServerError,
            err.to_string(),
            None,
        )
    }
}

impl From<ModelError> for ControllerError {
    fn from(err: ModelError) -> Self {
        let backtrace: Backtrace = if let Some(backtrace) =
            headless_lms_utils::error::backend_error::BackendError::backtrace(&err)
        {
            backtrace.clone()
        } else {
            Backtrace::new()
        };
        let span_trace = err.span_trace().clone();
        match err.error_type() {
            ModelErrorType::RecordNotFound => Self::new_with_traces(
                ControllerErrorType::NotFound,
                err.to_string(),
                Some(err.into()),
                backtrace,
                span_trace,
            ),
            ModelErrorType::NotFound => Self::new_with_traces(
                ControllerErrorType::NotFound,
                err.to_string(),
                Some(err.into()),
                backtrace,
                span_trace,
            ),
            ModelErrorType::PreconditionFailed => Self::new_with_traces(
                ControllerErrorType::BadRequest,
                err.message().to_string(),
                Some(err.into()),
                backtrace,
                span_trace,
            ),
            ModelErrorType::PreconditionFailedWithCMSAnchorBlockId { description, id } => {
                Self::new_with_traces(
                    ControllerErrorType::BadRequestWithData(ErrorData::BlockId(*id)),
                    description.to_string(),
                    Some(err.into()),
                    backtrace,
                    span_trace,
                )
            }
            ModelErrorType::DatabaseConstraint { description, .. } => Self::new_with_traces(
                ControllerErrorType::BadRequest,
                description.to_string(),
                Some(err.into()),
                backtrace,
                span_trace,
            ),
            ModelErrorType::InvalidRequest => Self::new_with_traces(
                ControllerErrorType::BadRequest,
                err.message().to_string(),
                Some(err.into()),
                backtrace,
                span_trace,
            ),
            _ => Self::new_with_traces(
                ControllerErrorType::InternalServerError,
                err.to_string(),
                Some(err.into()),
                backtrace,
                span_trace,
            ),
        }
    }
}

impl From<UtilError> for ControllerError {
    fn from(err: UtilError) -> Self {
        let backtrace: Backtrace = if let Some(backtrace) =
            headless_lms_utils::error::backend_error::BackendError::backtrace(&err)
        {
            backtrace.clone()
        } else {
            Backtrace::new()
        };
        let span_trace = err.span_trace().clone();
        Self::new_with_traces(
            ControllerErrorType::InternalServerError,
            err.to_string(),
            Some(err.into()),
            backtrace,
            span_trace,
        )
    }
}