enable Error::new(u16, error) and Error::from_str(u16, msg)

change status that Error::new and Error::from_str argument
status: StatusCode
->
status: S
S: TryInto<StatusCode>
S::Error: Debug
This commit is contained in:
yusuke-ota 2020-08-07 19:10:52 +09:00
parent bbd63d8f57
commit d0aed08a39
2 changed files with 43 additions and 5 deletions

View File

@ -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.
///
@ -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

View File

@ -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, "Un Existed 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, "Un Existed");
}