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
// Copyright (c) 2021 ruarango developers
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.

//! `ruarango` error

use crate::model::{doc::output::DocErr, BaseErr};
use serde::ser::{Serialize, SerializeStruct, Serializer};
use std::error::Error;
#[cfg(test)]
use std::num::ParseIntError;

/// When bad things happen
#[derive(thiserror::Error, Clone, Debug, Eq, PartialEq)]
#[allow(variant_size_differences)]
pub enum RuarangoErr {
    ///
    #[error("{}\nInvalid Body: {}", err, body)]
    InvalidBody {
        ///
        err: String,
        ///
        body: String,
    },
    ///
    #[error("Unreachable: {}", msg)]
    Unreachable {
        ///
        msg: String,
    },
    ///
    #[error("You have supplied an invalid connection url")]
    InvalidConnectionUrl,
    ///
    #[error("Invalid document response: {}\n{}", status, doc_err(err))]
    InvalidDocResponse {
        ///
        status: u16,
        ///
        err: Option<DocErr>,
    },
    ///
    #[error("Invalid cursor response: {}", status)]
    InvalidCursorResponse {
        ///
        status: u16,
    },
    ///
    #[error("You are not authorized to perform the request action")]
    Forbidden {
        ///
        err: Option<DocErr>,
    },
    ///
    #[error("The server can not find the requested resource.")]
    NotFound {
        ///
        err: Option<DocErr>,
    },
    ///
    #[error("The document you requested has not been modified")]
    NotModified,
    ///
    #[error("A precondition has failed: '{}'", doc_err(err))]
    PreconditionFailed {
        ///
        err: Option<DocErr>,
    },
    ///
    #[error(
        "The server could not understand the request due to invalid syntax.: '{}'",
        doc_err(err)
    )]
    BadRequest {
        ///
        err: Option<DocErr>,
    },
    ///
    #[error("A precondition has failed: '{}'", doc_err(err))]
    Conflict {
        ///
        err: Option<DocErr>,
    },
    ///
    #[error("A cursor request error has occurred: {}", base_err(err))]
    Cursor {
        ///
        err: Option<BaseErr>,
    },
    #[cfg(test)]
    #[error("Unable to parse the given value")]
    ParseInt(#[from] ParseIntError),
    #[cfg(test)]
    #[error("A test error has occurred: {}", val)]
    TestError { val: String },
    #[cfg(test)]
    #[error("You have requested an invalid mock")]
    InvalidMock,
}

impl Serialize for RuarangoErr {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut state = serializer.serialize_struct("RuarangoErr", 2)?;
        state.serialize_field("reason", &format!("{}", self))?;
        if let Some(source) = self.source() {
            state.serialize_field("source", &format!("{}", source))?;
        }
        state.end()
    }
}

fn doc_err(err: &Option<DocErr>) -> String {
    err.as_ref().map_or_else(
        || "No matching document found".to_string(),
        ToString::to_string,
    )
}

fn base_err(err: &Option<BaseErr>) -> String {
    err.as_ref()
        .map_or_else(|| "cursor error".to_string(), ToString::to_string)
}

#[cfg(test)]
impl From<&str> for RuarangoErr {
    fn from(val: &str) -> Self {
        Self::TestError {
            val: val.to_string(),
        }
    }
}

#[cfg(test)]
impl From<String> for RuarangoErr {
    fn from(val: String) -> Self {
        Self::TestError { val }
    }
}

#[cfg(test)]
mod test {
    use super::RuarangoErr::{self, TestError};
    use anyhow::Result;

    #[test]
    fn serialize_with_source_works() -> Result<()> {
        match str::parse::<usize>("test") {
            Ok(_) => panic!("this shouldn't happen"),
            Err(e) => {
                let err: RuarangoErr = e.into();
                let result = serde_json::to_string(&err)?;
                assert_eq!("{\"reason\":\"Unable to parse the given value\",\"source\":\"invalid digit found in string\"}", result);
            }
        }

        Ok(())
    }

    #[test]
    fn serialize_no_source_works() -> Result<()> {
        let err: RuarangoErr = TestError {
            val: "test".to_string(),
        };
        let result = serde_json::to_string(&err)?;
        assert_eq!("{\"reason\":\"A test error has occurred: test\"}", result);
        Ok(())
    }

    #[test]
    fn from_str_works() -> Result<()> {
        let err: RuarangoErr = "test".into();
        let result = serde_json::to_string(&err)?;
        assert_eq!("{\"reason\":\"A test error has occurred: test\"}", result);
        Ok(())
    }

    #[test]
    fn from_string_works() -> Result<()> {
        let err: RuarangoErr = String::from("test").into();
        let result = serde_json::to_string(&err)?;
        assert_eq!("{\"reason\":\"A test error has occurred: test\"}", result);
        Ok(())
    }
}