Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use std::error::Error as StdError;
use std::fmt::{self, Debug, Display};

use crate::StatusCode;
use std::convert::TryInto;

/// A specialized `Result` type for HTTP operations.
///
Expand All @@ -23,24 +24,33 @@ impl Error {
/// The error type must be threadsafe and 'static, so that the Error will be
/// as well. If the error type does not provide a backtrace, a backtrace will
/// be created here to ensure that a backtrace exists.
pub fn new(status: StatusCode, error: impl Into<anyhow::Error>) -> Self {
pub fn new<S>(status: S, error: impl Into<anyhow::Error>) -> Self
where
S: TryInto<StatusCode>,
S::Error: Debug,
{
Self {
status,
status: status
.try_into()
.expect("Could not convert into a valid `StatusCode`"),
error: error.into(),
}
}

/// Create a new error object from static string.
pub fn from_str<M>(status: StatusCode, msg: M) -> Self
pub fn from_str<S, M>(status: S, msg: M) -> Self
where
S: TryInto<StatusCode>,
S::Error: Debug,
M: Display + Debug + Send + Sync + 'static,
{
Self {
status,
status: status
.try_into()
.expect("Could not convert into a valid `StatusCode`"),
error: anyhow::Error::msg(msg),
}
}

/// Create a new error from a message.
pub(crate) fn new_adhoc<M>(message: M) -> Error
where
Expand Down
28 changes: 28 additions & 0 deletions tests/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,3 +96,31 @@ fn normal_error_into_http_types_error() {
);
assert_eq!(http_types_error.status(), StatusCode::ImATeapot);
}

#[test]
fn u16_into_status_code_in_http_types_error() {
let http_types_error = Error::new(404, io::Error::new(io::ErrorKind::Other, "Not Found"));
let http_types_error2 = Error::new(
StatusCode::NotFound,
io::Error::new(io::ErrorKind::Other, "Not Found"),
);
assert_eq!(http_types_error.status(), http_types_error2.status());

let http_types_error = Error::from_str(404, "Not Found");
assert_eq!(http_types_error.status(), StatusCode::NotFound);
}

#[test]
#[should_panic]
fn fail_test_u16_into_status_code_in_http_types_error_new() {
let _http_types_error = Error::new(
1000,
io::Error::new(io::ErrorKind::Other, "Incorrect status code"),
);
}

#[test]
#[should_panic]
fn fail_test_u16_into_status_code_in_http_types_error_from_str() {
let _http_types_error = Error::from_str(1000, "Incorrect status code");
}