refactor: replace `as_str()` on message enums with `impl Display`
- automatic formatting of printed errors
- its better to not reinvent the wheel
- comes with `to_string()`
Diff
src/data.rs | 8 ++++----
src/errors.rs | 23 ++++++++++++++---------
src/main.rs | 10 +++++-----
3 files changed, 23 insertions(+), 18 deletions(-)
@@ -36,7 +36,7 @@ impl Queryable for LicenseDatabase {
.join("\n");
if result.is_empty() {
log::warn!("{}", ErrorMsg::NoLicensesAvailable.as_str());
log::warn!("{}", ErrorMsg::NoLicensesAvailable);
None
} else {
Some(result)
@@ -61,7 +61,7 @@ impl Queryable for LicenseDatabase {
.join("\n");
if result.is_empty() {
log::warn!("{}", ErrorMsg::NoLicensesAvailable.as_str());
log::warn!("{}", ErrorMsg::NoLicensesAvailable);
None
} else {
Some(result)
@@ -87,11 +87,11 @@ impl LicenseDatabase {
match std::fs::read_to_string(db_path.as_path()) {
Ok(contents) => {
let database: LicenseDatabase = serde_yaml::from_str(&contents).unwrap();
log::info!("{}", SuccessMsg::DatabaseLoaded.as_str());
log::info!("{}", SuccessMsg::DatabaseLoaded);
Some(database)
}
Err(_) => {
log::error!("{}", ErrorMsg::DatabaseError.as_str());
log::error!("{}", ErrorMsg::DatabaseError);
None
}
}
@@ -1,3 +1,5 @@
use std::fmt::Display;
#[derive(Debug)]
pub enum ErrorMsg {
DatabaseError,
@@ -7,17 +9,19 @@ pub enum ErrorMsg {
LicenseReadError,
}
impl ErrorMsg {
pub fn as_str(&self) -> &str {
match *self {
impl Display for ErrorMsg {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let message = match self {
ErrorMsg::LicenseReadError => "Unable to read license file:",
ErrorMsg::DatabaseError => "Unable to load or parse license database.",
ErrorMsg::NoLicensesAvailable => "No licenses found.",
ErrorMsg::InvalidLicenseRequest => { ErrorMsg::InvalidLicenseRequest => {
"Invalid license. use the 'list' or 'list/all' endpoints to see defined licenses."
}
ErrorMsg::InvalidLicense => "Invalid license requested:",
}
};
write!(f, "{}", message)
}
}
@@ -26,10 +30,11 @@ pub enum SuccessMsg {
DatabaseLoaded,
}
impl SuccessMsg {
pub fn as_str(&self) -> &str {
match *self {
impl Display for SuccessMsg {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let message = match self {
SuccessMsg::DatabaseLoaded => "Database loaded successfully!",
}
};
write!(f, "{}", message)
}
}
@@ -116,7 +116,7 @@ async fn get_license_list(req: tide::Request<RunningConfig>) -> tide::Result<Res
Some(licenses) => Ok(build_response(StatusCode::Ok, format!("{}", licenses))),
None => Ok(build_response(
StatusCode::NotFound,
String::from(ErrorMsg::NoLicensesAvailable.as_str()),
ErrorMsg::NoLicensesAvailable.to_string(),
)),
}
}
@@ -126,7 +126,7 @@ async fn get_detailed_license_list(req: tide::Request<RunningConfig>) -> tide::R
Some(licenses) => Ok(build_response(StatusCode::Ok, format!("{}", licenses))),
None => Ok(build_response(
StatusCode::NotFound,
String::from(ErrorMsg::NoLicensesAvailable.as_str()),
ErrorMsg::NoLicensesAvailable.to_string(),
)),
}
}
@@ -153,7 +153,7 @@ async fn get_requested_license(req: tide::Request<RunningConfig>) -> tide::Resul
Err(_) => {
log::error!(
"{} '{}'.",
ErrorMsg::LicenseReadError.as_str(),
ErrorMsg::LicenseReadError,
license_file_path.to_string_lossy().to_string()
);
@@ -162,7 +162,7 @@ async fn get_requested_license(req: tide::Request<RunningConfig>) -> tide::Resul
}
}
None => {
log::error!("{} '{}'", ErrorMsg::InvalidLicense.as_str(), request);
log::error!("{} '{}'", ErrorMsg::InvalidLicense, request);
error_response(request)
}
};
@@ -173,6 +173,6 @@ async fn get_requested_license(req: tide::Request<RunningConfig>) -> tide::Resul
fn error_response(_req: &str) -> Response {
build_response(
StatusCode::NotFound,
format!("{}", ErrorMsg::InvalidLicenseRequest.as_str()).to_string(),
format!("{}", ErrorMsg::InvalidLicenseRequest),
)
}