Skip to content

Commit bbd63d8

Browse files
committed
support anyhow::Error into http_types:Error
1 parent d8944ce commit bbd63d8

File tree

2 files changed

+30
-13
lines changed

2 files changed

+30
-13
lines changed

src/error.rs

Lines changed: 4 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -23,13 +23,10 @@ impl Error {
2323
/// The error type must be threadsafe and 'static, so that the Error will be
2424
/// as well. If the error type does not provide a backtrace, a backtrace will
2525
/// be created here to ensure that a backtrace exists.
26-
pub fn new<E>(status: StatusCode, error: E) -> Self
27-
where
28-
E: StdError + Send + Sync + 'static,
29-
{
26+
pub fn new(status: StatusCode, error: impl Into<anyhow::Error>) -> Self {
3027
Self {
3128
status,
32-
error: anyhow::Error::new(error),
29+
error: error.into(),
3330
}
3431
}
3532

@@ -119,15 +116,9 @@ impl Debug for Error {
119116
}
120117
}
121118

122-
impl<E> From<E> for Error
123-
where
124-
E: StdError + Send + Sync + 'static,
125-
{
119+
impl<E: Into<anyhow::Error>> From<E> for Error {
126120
fn from(error: E) -> Self {
127-
Self {
128-
error: anyhow::Error::new(error),
129-
status: StatusCode::InternalServerError,
130-
}
121+
Self::new(StatusCode::InternalServerError, error)
131122
}
132123
}
133124

tests/error.rs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,3 +70,29 @@ fn option_ext() {
7070
let err = res.unwrap_err();
7171
assert_eq!(err.status(), StatusCode::NotFound);
7272
}
73+
74+
#[test]
75+
fn anyhow_error_into_http_types_error() {
76+
let anyhow_error =
77+
anyhow::Error::new(std::io::Error::new(std::io::ErrorKind::Other, "irrelevant"));
78+
let http_types_error: Error = anyhow_error.into();
79+
assert_eq!(http_types_error.status(), StatusCode::InternalServerError);
80+
81+
let anyhow_error =
82+
anyhow::Error::new(std::io::Error::new(std::io::ErrorKind::Other, "irrelevant"));
83+
let http_types_error: Error = Error::new(StatusCode::ImATeapot, anyhow_error);
84+
assert_eq!(http_types_error.status(), StatusCode::ImATeapot);
85+
}
86+
87+
#[test]
88+
fn normal_error_into_http_types_error() {
89+
let http_types_error: Error =
90+
std::io::Error::new(std::io::ErrorKind::Other, "irrelevant").into();
91+
assert_eq!(http_types_error.status(), StatusCode::InternalServerError);
92+
93+
let http_types_error = Error::new(
94+
StatusCode::ImATeapot,
95+
std::io::Error::new(std::io::ErrorKind::Other, "irrelevant"),
96+
);
97+
assert_eq!(http_types_error.status(), StatusCode::ImATeapot);
98+
}

0 commit comments

Comments
 (0)