use dropshot::HttpError;
use http::StatusCode;
use serde::{Deserialize, Serialize};
use serde_json::to_string_pretty;
#[derive(Debug, Serialize, Deserialize)]
pub struct Error {
pub status: String,
pub code: String,
pub message: String,
}
impl Into<HttpError> for Error {
fn into(self) -> HttpError {
let status_code = match self.status.as_str() {
"400" => StatusCode::BAD_REQUEST,
"404" => StatusCode::NOT_FOUND,
_ => StatusCode::BAD_GATEWAY,
};
HttpError {
status_code: status_code,
error_code: Some(self.code),
external_message: self.message.clone(),
internal_message: self.message,
}
}
}
pub fn new_not_found_error(msg: &str) -> Error {
Error {
status: String::from("404"),
code: String::from("NOT_FOUND"),
message: msg.to_string(),
}
}
pub fn new_invalid_state_error(msg: &str) -> Error {
Error {
status: String::from("400"),
code: String::from("INVALID_STATE"),
message: msg.to_string(),
}
}
pub fn new_application_error<T: Serialize>(code: &str, payload: T) -> Error {
Error {
status: String::from("400"),
code: code.to_string(),
message: to_string_pretty(&payload).unwrap(),
}
}
pub fn new_server_error(msg: &str) -> Error {
Error {
status: String::from("500"),
code: String::from("SERVER_ERROR"),
message: msg.to_string(),
}
}
#[test]
fn error_conversion_test() {
let error = new_not_found_error("the requested resource could not be found");
let http_error: HttpError = error.into();
dbg!(http_error);
}