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
use async_trait::async_trait;
use std::convert::Infallible;
use std::error::Error as StdError;
use std::fmt;
use crate::{Depot, Request, Response, Writer};
type BoxError = Box<dyn std::error::Error + Send + Sync>;
pub struct Error {
inner: BoxError,
}
impl Error {
#[inline]
pub fn new<E: Into<BoxError>>(err: E) -> Error {
Error { inner: err.into() }
}
}
impl fmt::Debug for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self.inner, f)
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.inner, f)
}
}
impl StdError for Error {}
impl From<Infallible> for Error {
fn from(infallible: Infallible) -> Error {
match infallible {}
}
}
#[cfg(debug_assertions)]
#[async_trait]
impl Writer for Error {
#[inline]
async fn write(mut self, _req: &mut Request, _depot: &mut Depot, res: &mut Response) {
res.set_http_error(crate::http::errors::InternalServerError().with_detail(&self.to_string()));
}
}
#[cfg(not(debug_assertions))]
#[async_trait]
impl Writer for Error {
#[inline]
async fn write(mut self, _req: &mut Request, _depot: &mut Depot, res: &mut Response) {
res.set_status_code(crate::http::StatusCode::INTERNAL_SERVER_ERROR);
}
}
#[test]
fn error_size_of() {
assert_eq!(::std::mem::size_of::<Error>(), ::std::mem::size_of::<usize>() * 2);
}
#[cfg(debug_assertions)]
#[cfg(feature = "anyhow")]
#[async_trait]
impl Writer for ::anyhow::Error {
async fn write(mut self, _req: &mut Request, _depot: &mut Depot, res: &mut Response) {
res.set_http_error(crate::http::errors::InternalServerError().with_detail(&self.to_string()));
}
}
#[cfg(not(debug_assertions))]
#[cfg(feature = "anyhow")]
#[async_trait]
impl Writer for ::anyhow::Error {
async fn write(mut self, _req: &mut Request, _depot: &mut Depot, res: &mut Response) {
res.set_http_error(crate::http::errors::InternalServerError());
}
}
#[cfg(test)]
mod tests {
use crate::http::*;
use super::*;
#[tokio::test]
#[cfg(feature = "anyhow")]
async fn test_anyhow() {
let mut req = Request::default();
let mut res = Response::default();
let mut depot = Depot::new();
let err: ::anyhow::Error = Error::new("detail message").into();
err.write(&mut req, &mut depot, &mut res).await;
assert_eq!(res.status_code(), Some(crate::http::StatusCode::INTERNAL_SERVER_ERROR));
}
#[tokio::test]
async fn test_error() {
let mut req = Request::default();
let mut res = Response::default();
let mut depot = Depot::new();
let err = Error::new("detail message");
err.write(&mut req, &mut depot, &mut res).await;
assert_eq!(res.status_code(), Some(crate::http::StatusCode::INTERNAL_SERVER_ERROR));
}
}