Coverage Report

Created: 2024-02-20 21:15

/builds/xfbs/cindy/src/server/error.rs
Line
Count
Source (jump to first uncovered line)
1
use axum::{
2
    http::StatusCode,
3
    response::{IntoResponse, Response},
4
    Json,
5
};
6
use cindy_common::ErrorResponse;
7
use thiserror::Error;
8
use tokio::task::JoinError;
9
10
6
#[derive(
E3
rror,
D2
ebu
g2
)]
11
pub enum Error {
12
    #[error("waiting for blocking task")]
13
    Task(#[from] JoinError),
14
    #[error(transparent)]
15
    Other(#[from] anyhow::Error),
16
    #[error(transparent)]
17
    IO(#[from] std::io::Error),
18
    #[error("not found")]
19
    NotFound,
20
    #[error(transparent)]
21
    Sqlite(#[from] rusqlite::Error),
22
}
23
24
impl Error {
25
7
    fn status(&self) -> StatusCode {
26
7
        match self {
27
4
            Error::NotFound => StatusCode::NOT_FOUND,
28
3
            _ => StatusCode::INTERNAL_SERVER_ERROR,
29
        }
30
7
    }
31
}
32
33
impl IntoResponse for Error {
34
3
    fn into_response(self) -> Response {
35
3
        let status = self.status();
36
3
        let response = ErrorResponse::new(&self);
37
3
        (status, Json(response)).into_response()
38
3
    }
39
}
40
41
#[cfg(test)]
42
mod tests {
43
    use super::*;
44
    use anyhow::anyhow;
45
46
2
    fn errors() -> Vec<Error> {
47
2
        vec![
48
2
            Error::NotFound,
49
2
            Error::Other(anyhow::anyhow!("Anyhow error")),
50
2
        ]
51
2
    }
52
53
1
    #[test]
54
1
    fn test_response() {
55
3
        for 
error2
in errors() {
56
2
            let status = error.status();
57
2
            let response = error.into_response();
58
2
            assert_eq!(response.status(), status);
59
        }
60
1
    }
61
62
1
    #[test]
63
1
    fn test_debug() {
64
3
        for 
error2
in errors() {
65
2
            println!("{error:?}");
66
2
        }
67
1
    }
68
69
1
    #[test]
70
1
    fn test_status() {
71
1
        assert_eq!(Error::NotFound.status(), StatusCode::NOT_FOUND);
72
1
        assert_eq!(
73
1
            Error::Other(anyhow!("Error")).status(),
74
1
            StatusCode::INTERNAL_SERVER_ERROR
75
1
        );
76
1
    }
77
}